Search code examples
phparraysforeachwhile-loopassociative-array

php var with multiple assoc arrays, get values one array at a time


Originally I was taking an uploaded .csv file and iterating through the values one row at a time.. with the below while loop.

 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
     var_dump($data);
     $importIt = $repo->impThreeCSV($which, $data);
 }

I have redone the .csv upload functionality to now be a web form where I send json to the PHP file on a 'save button'. I now have a variable with multiple associative arrays in it..

    $fd = json_decode($df, true);
    var_dump($fd);

For instance the dump above contains multiple arrays such as below: i.e. (~300 similar arrays as below).

array (size=806)
  0 => 
    array (size=18)
      'ATM_ID' => string 'AFF-MIL-TWR' (length=11)
      'FAC_IDENT' => string 'AFF' (length=3)
      'LG_NAME' => string 'BLACH BLAH ACADEMY' (length=20)
      'BASIC_TP' => string 'MIL-TWR' (length=7)
      .................
  • How can I iterate through the VALUES only in these arrays, one at a time in the same fashion as my original while loop.. (this would be ideal so I don't have to redo the whole back-end).

  • I am having issues handling the multiple arrays and getting the values only out..

  • I have tried the below two attempts, I just get 'arrayarrayarray' or similar in var_dump. Do I need to break out each array into it's own var? What am I doing wrong here? Do I need to run a count on how many arrays consist in my var?

     $fd = json_decode($df, true);
     var_dump($fd);
    
     $data = array_values($fd);
     foreach ($data as $array_key) {
         echo $array_key;
     }
    
     $array_keys = array_keys($fd);
         foreach ($array_keys as $array_key) {
         echo $array_key;
     }
    

P.S. No, I can't use pandas, I wish.


Solution

  • Assuming you want to process the data in the same way as your original piece of code, you would just use something like:

    foreach ($fd as $data) {
        $importIt = $repo->impThreeCSV($which, array_values($data));
    }
    

    Note I've used array_values to convert $data from an associative array to a numerically indexed one, i.e. the same format as fgetcsv returns. This may - dependent on your $repo->impThreeCSV code - not be necessary.