0

Hello I have a PHP script that returns an array like that:

array(2) {
    [0]=> array(1) {
        ["Code"]=> int(100)
    }
    [1]=> array(1) {
        ["Drivers"]=> array(1) {
            [0]=> array(7) {
                ["RowID"]=> string(3) "139"
                ["DriverName"]=> string(7) "John"
                ["DriverAlias"]=> string(6) "DRX7"
                ["DriverEmail"]=> string(23) "xxx@hotmail.fr"
                ["DriverPhone"]=> string(12) "8888888888"
                ["DriverActivity"]=> string(8) "Inactive"
                ["DriversActiveDates"]=> array(1) {
                    [0]=> string(9) "2014-2-15"
                }
            }
        }
    }
}

How can I read or print every information on this array? Thanks

George Brighton
  • 5,131
  • 9
  • 27
  • 36
OussamaLord
  • 1,073
  • 5
  • 28
  • 39

3 Answers3

0

try this;

foreach($arr as $a){
    foreach($a as $key => $value){
        if(is_array($value)){
            foreach($value as $key2 => $value2){
                 echo'key: '.$key2.' value: '.$value2;
            }
        }
        else{
            echo'key: '.$key.' value: '.$value;
        }
    }
}
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
0

Since you have arrays within arrays to an unknown depth, you have to use a recursive function to be sure you get every key/value pair.

array_walk_recursive($your_array, function($item, $key){
    if (!is_array($item)) print "{$key}: {$item}";
});

Right in the php docs for array_walk_recursive is another example:

$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
  echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');

http://php.net/manual/en/function.array-walk-recursive.php

willoller
  • 7,106
  • 1
  • 35
  • 63
  • Woow, all this code, I was able to print the first RowID like that : echo $arrayOfDrivers[1]['Drivers'][0]['RowID']; is it not correct? – OussamaLord Jan 18 '14 at 20:09
  • 1
    You asked to print everything. If you want to print a *specific* thing, then yes you are doing it correctly. – willoller Jan 18 '14 at 20:10
0

you can try this

    function printArray($value, $key){
        echo sprintf('%s => %s', $key, $value);
    }
    array_walk_recursive($a, 'printArray');
Amine Matmati
  • 283
  • 1
  • 9
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 07:54