Thursday, 30 August 2018

Looping across a multidimensional array in php

I have this multidimensional array in php and I need be able to access all the elements including the first element "Computers". I need to turn this array into two arrays and i used this loop

    $i = 0;
$left = array();
$right = array();
    foreach ($all_products as $product) {
    if ($i++ % 2 == 0) {

        $left[]  = $product;
    } else {
        $right[] = $product;
    }
}

Here is the structure of $all_products
Array (
  [Computers] => Array (
    [macbook] => Array ( [price] => 575
                           [quantity] => 3
                           [image] => T-SMALL-blue.png
                           [descr] => osx
                          )
    [windows] => Array ( [price] => 285
                         [quantity] => 1
                         [image] => TU220-blue.png
                         [descr] => something windows )
                        )
 [Screens] => Array (
    [FIREBOX S5510 15", SPKRS ] => Array ( [price] => 489
                                           [quantity] => 3
                                           [image] => [descr] => SPKRS
                           )
                        )
 [Software] => Array ( .....

but when i logger $left or $right
[0] => Array (
  [macbook] => Array (
     [price] => 575
     [quantity] => 3
     [image] => TOWER-PC-LENOVO-SMALL-blue.png
     [descr] => osx
             )
  [windows] => Array (
     [price] => 575
     [quantity] => 3
     [image] => TOWER-PC-LENOVO-SMALL-blue.png
     [descr] => something windows
)
[1] => Array

where is the text "Computers", "Screens"

You are adding next element to $left and $right when you use [], and its numerical. Try:
foreach ($all_products as $key=>$product) {
if ($i++ % 2 == 0) {
        $left[$key][]  = $product;
    } else {
        $right[$key][] = $product;
    }
}

0 comments:

Post a Comment