Text file data to an associative array in PHP and search data -




i'm beginner in php. have text file this:

name-id-number abid-01-80 sakib-02-76 

i can take data array unable take associative array. want following things:

  • take data associative array in php.
  • search number using id.
  • find out total of numbers

i believe understand want, , it's simple. first need read file php array. can done this:

$filedata = file($filename, file_ignore_new_lines);

now build desired array using foreach() loop, explode , standard array assignment. search requirement unclear, in example, make associated array element array associative array keys 'id' , 'num'.

as create new array, can compute sum, demonstrated.

<?php  $filedata = array('abid-01-80', 'sakib-02-76');  $linearray = array(); $numtotal = 0;  foreach ($filedata $line) {     $values = explode('-', $line);     $numtotal += $values[2];     $linearray[$values[0]] = array('id' => $values[1], 'num' => $values[2]); }  echo "total: $numtotal\n\n"; var_dump($linearray); 

you can see code demonstrated here

updated response:

keep in mind notices not errors. notifiying code cleaner, typically suppressed in production.

the undefined variable notices coming because using:

$var += $var without having initialized $var previously. note inconsistent in practice. example initialized $numtotal, didn't notice when used same approach increment it.

simply add below $numtotal = 0:

$count = 0; $counteighty = 0; 

your other notices occurring due blank line or string in input not follow pattern expected. when explode executed not returning array 3 elements, when try , reference $values = explode('-', $line); need make sure $line not empty string before process it. add sanity check like:

enter code hereif (count($values) === 3) { // it's ok process





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -