JimB814
JimB814

Reputation: 510

Iterating over multidimensional array where some arrays might have no elements

I have a $products array like this:

Array
(
    [0] => Array
        (
            [0] => 1001
            [1] => 1002
        )

    [1] => 
    [2] => 
    [3] => 
    [4] => 
    [5] => 
    [6] => 
    [7] => 
)

I want to loop through it and create a one-level array comprised only of the non-empty array data like this:

$newArr = [
    [0] => 1001,
    [1] => 1002
]

My foreach loop that I thought would work throws an error ('Invalid argument supplied for foreach()').

The foreach loop looks like this:

$idArr = [];
foreach($products as $value) {
    foreach ($value as $id) {
        echo $id . '<br>';
        $idArr[] = $id;
    }
}

The two values echo suggesting the code is correct, but it's not. I am unable to store the iterated $id value into $idArr[].

If anyone can spot my error or errors, I would appreciate it.

Thanks!

Upvotes: 1

Views: 61

Answers (4)

Osama
Osama

Reputation: 3030

$idArr = array();
foreach($products as $value) {
    if(is_array($value)){
        foreach ($value as $id) {
                $idArr[] = $id;
         }
      }
 }

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

You don't need to change your code much, you can just skip the inner loop if there's no value.

$idArr = [];
foreach($products as $value) {
    if (!$value) continue;   // continue to next iteration without executing the inner loop
    foreach ($value as $id) {
        $idArr[] = $id;
    }
}

Or enclose the inner loop in an if ($value) ... block. However you like, as long as you're not trying to iterate arrays that aren't there.

Upvotes: 1

Shobi
Shobi

Reputation: 11481

You could use PHP Spl RecursiveIteratorIterator

$array = array(1,2,array(3,4, array(5,6,7), 8),[0=>1, 1=> [0=>null]], 9);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
  echo $v, " ";
}

prints

1 2 3 4 5 6 7 8 1 9

reference modified to suit your example

Upvotes: 0

Sergey B.
Sergey B.

Reputation: 83

<?php
$arrayTest = [
        'country' => [
            'Russian Federation' => [
                'Region' => [
                    'Moscow',
                    'Moscow',
                    'Moscow'
                ],
                'Moscow', 
                'Moscow', 
                'Moscow'
            ],
            "United States of America" => [
                'Moscow', 
                'Moscow', 
                'Moscow'
            ],
            "China" => [
                'Moscow', 
                'Moscow', 
                'Moscow'
            ]
        ],

        'union' => [
            'Moscow', 
            'Moscow'
        ], 

        'status' => 1, 

        'age' => 34
    ];

$result = [];
array_walk_recursive($arrayTest, function ($item, $key) use (&$result) {
    $result[] = $item;    
});
print_r($result);
?>

Upvotes: 0

Related Questions