1

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.

4
  • 1
    You could write a loop in a loop. Commented Nov 2, 2018 at 6:37
  • 3
    Please add an example array in code. Also, what is is the error that is appearing for 1 entry? Commented Nov 2, 2018 at 6:37
  • 1
    In the screenshot there is no bDate is that correct? Commented Nov 2, 2018 at 6:39
  • 1
    sorry I wrote wrong, bDate should be bItem Commented Nov 2, 2018 at 6:58

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.