widiramadhan
widiramadhan

Reputation: 35

Loop over an array of unknown depth

How to loop an array if the data is 1 level or more than 1 level?

I tried it with

foreach ($array['bGeneral'] as $item) {
    echo $item['bItem'];
}

but for arrays that have 1 level of data an error occurs.

Upvotes: 1

Views: 114

Answers (2)

Agnius Vasiliauskas
Agnius Vasiliauskas

Reputation: 11277

Don't forget recursion - sometimes it is a best choise :

function scan_data($data, $path = null) {
    if (!is_array($data))
        echo "{$path} : {$data}\n";
    else
        foreach ($data as $k => $v)
            scan_data($v, $path . '/' . $k);
}

$data = [
    ['a' => 1,                    'b' => 2], 
    ['a' => ['c' => 3, 'd' => 4], 'b' => 5],
    ['a' => 1,                    'b' => ['e' => ['f' => 1, 'g' => 2], 'h' => 6] ]
   ];

scan_data($data);

Output:

/0/a : 1
/0/b : 2
/1/a/c : 3
/1/a/d : 4
/1/b : 5
/2/a : 1
/2/b/e/f : 1
/2/b/e/g : 2
/2/b/h : 6

Upvotes: 0

Nick
Nick

Reputation: 147216

Basically you need to check if the first element of $array['bGeneral'] is an array or a data value, and if so, process the data differently. You could try something like this:

if (isset($array['bGeneral']['bItem'])) {
    // only one set of values
    $item = $array['bGeneral'];
    // process item
}
else {
    // array of items
    foreach ($array['bGeneral'] as $item) {
        // process item
    }
}

To avoid duplication of code, you will probably want to put the item processing code in a function.

Alternatively you could create a multi-dimensional array when you only have one value and then continue processing as you do with multiple values:

if (isset($array['bGeneral']['bItem'])) {
    $array['bGeneral'] = array($array['bGeneral']);
}
foreach ($array['bGeneral'] as $item) {
    // process item
}

Upvotes: 2

Related Questions