我有一个数组在每个索引上都有这样的值我有一个嵌套数组[cats]
和[products]
Array
(
[0] => Array
(
[cat] => 6,
[products] => 3
),
[1] => Array
(
[cat] => 6,
[products] => 4
),
[2] => Array
(
[cat] => 7,
[products] => 9
)
)
我希望将此数组更改为具有相同值的所有[cats]
索引合并为单个索引,并将这些索引的[products]
索引合并为嵌套数组
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;
}
}
答案 0 :(得分:2)
正如其他人所说,你应该从foreach
<?php
$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 = (array) $newProducts[$item['cat']]['products'];
$newProducts[$item['cat']]['products'] = array_merge($currentValue, (array) $item['products']);
} else {
$newProducts[$item['cat']] = $item;
}
}
var_dump(array_values($newProducts));
输出如下:
array(2) {
[0]=>
array(2) {
["cat"]=>
int(6)
["products"]=>
array(2) {
[0]=>
int(3)
[1]=>
int(4)
}
}
[1]=>
array(2) {
["cat"]=>
int(7)
["products"]=>
int(9)
}
}
答案 1 :(得分:2)
试试这个:
<?php
$array = array(
array(
'cat'=>6,
'product'=>3,
),
array(
'cat'=>6,
'product'=>4,
),
array(
'cat'=>5,
'product'=>9,
),
);
$catIndex = array();
foreach($array as $subarray)
{
if(!isset($catIndex[$subarray['cat']]))
$catIndex[$subarray['cat']] = array('cat'=>$subarray['cat'], 'products'=>array());
$catIndex[$subarray['cat']]['products'][] = $subarray['product'];
}
var_dump(array_values($catIndex));
工作示例:CLICK!
答案 2 :(得分:0)
此脚本可能会有所帮助。
忽略$ arr1,$ arr2,$ arr3。我只是创建它们来制作像你一样的数组。
<div id="add_item_modal" class="modal" data-backdrop="" role="dialog">
输出 -
$arr1 = array(
'cat' => 6,
'products' => 3,
);
$arr2 = array(
'cat' => 6,
'products' => 4,
);
$arr3 = array(
'cat' => 7,
'products' => 9,
);
$arr4 = array($arr1, $arr2, $arr3);
print_r($arr4);
$n = count($arr4);
for($i=0; $i<$n; $i++){
if($arr4[$i]['cat'] == $arr4[$i+1]['cat']){
$arr5[$i]['cat'] = $arr4[$i]['cat'];
$arr5[$i]['products'] = array($arr4[$i]['products'],$arr4[$i+1]['products']);
}
else {
$arr5[] = $arr4[$i+1];
}
}
array_pop($arr5); // just to delete the last null index of the array,
//created by the loop.
print_r($arr5)