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_produc开发者_JAVA百科ts 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;
}
}
You need to use a foreach
loop with $key
variable:
foreach ($all_products as $arrayIndex=>$product) {
this variable ($arrayIndex
, can be named anything for sure), will hold the array indexes strings inside the foreach loop.
精彩评论