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) "[email protected]"
                ["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

3
  • That array is why you shouldn't drink before sitting down to code.
    – W.K.S
    Jan 18, 2014 at 20:01
  • If you just want to print it out then var_dump() should be all you need.
    – Lix
    Jan 18, 2014 at 20:02
  • No I would like to echo each key and its value please Jan 18, 2014 at 20:03

3 Answers 3

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

2
  • Woow, all this code, I was able to print the first RowID like that : echo $arrayOfDrivers[1]['Drivers'][0]['RowID']; is it not correct? Jan 18, 2014 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, 2014 at 20:10
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;
        }
    }
}
0

you can try this

    function printArray($value, $key){
        echo sprintf('%s => %s', $key, $value);
    }
    array_walk_recursive($a, 'printArray');
1
  • 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. Apr 9, 2022 at 7:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.