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
我在php中有这个多维数组,我需要能够访问所有元素,包括第一个元素“Computers”。我需要将这个数组转换成两个数组,然后使用这个循环
$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
这是$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"
文本“计算机”、“屏幕”在哪里?
2 个解决方案
#1
3
You are adding next element to $left and $right when you use [], and its numerical. Try:
当您使用[]及其数值时,您将向$left和$right添加next元素。试一试:
foreach ($all_products as $key=>$product) {
if ($i++ % 2 == 0) {
$left[$key][] = $product;
} else {
$right[$key][] = $product;
}
}
#2
2
You need to use a foreach
loop with $key
variable:
您需要使用带有$key变量的foreach循环:
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.
这个变量($arrayIndex,可以被命名为任何类型)将在foreach循环中保存数组索引字符串。
#1
3
You are adding next element to $left and $right when you use [], and its numerical. Try:
当您使用[]及其数值时,您将向$left和$right添加next元素。试一试:
foreach ($all_products as $key=>$product) {
if ($i++ % 2 == 0) {
$left[$key][] = $product;
} else {
$right[$key][] = $product;
}
}
#2
2
You need to use a foreach
loop with $key
variable:
您需要使用带有$key变量的foreach循环:
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.
这个变量($arrayIndex,可以被命名为任何类型)将在foreach循环中保存数组索引字符串。