【发布时间】:2016-06-22 07:53:48
【问题描述】:
我有一个数组,在每个索引上都有这样的值我有一个嵌套数组有[cats] 和[products]
Array
(
[0] => Array
(
[cat] => 6,
[products] => 3
),
[1] => Array
(
[cat] => 6,
[products] => 4
),
[2] => Array
(
[cat] => 7,
[products] => 9
)
)
我想更改这个数组,就像所有具有相同值的 [cats] 索引合并到单个索引中一样,这些索引中的 [products]index 合并到嵌套数组中
Array
(
[0] => Array
(
[cat] => 6
[products] => array(
[0]=>3,
[1]=>4 )
),
[1] => Array
(
[cat] => 7,
[products] => 9
)
)
我试过了,但我的代码不起作用我的代码是这样的
$products = array(
array(
'cat' => 6,
'products' => 3
),
array(
'cat' => 6,
'products' => 4
),
array(
'cat' => 7,
'products' => 9
)
);
$newProducts = array();
foreach ($products as $item) {
if (!empty($newProducts[$item['cat']])) {
$currentValue = $newProducts[$item['cat']]['products'];
$newProducts[$item['cat']]['products'] = $item['products'];
} else {
$newProducts[$item['cat']] = $item;
}
}
【问题讨论】:
-
到目前为止您尝试过什么?发布您迄今为止尝试过的尝试。
-
其实我很困惑我不知道该怎么做..
-
您可能已经浏览了一些搜索教程或代码,您可能已经尝试过一些东西,然后您可能已经在 SO 上发布了问题。或者你到目前为止还没有尝试过,直接在 SO 上发布
-
从写
foreach开始 -
遍历数组并生成一个包含子列表的新数组。我建议始终使用
[products]下的子数组,即使它只包含一个条目。这使得创建和以后使用它变得更容易(您不必为一种产品和多种产品处理不同的情况)。