我有一个多维数组。
Array
(
[0] => Array
(
[NAME] => FEMFAT
[VERSION] => 5.1
[VENDOR] => MAGNAECS
[END] => 2015-01-30
[USED_LICENSES] => 1
[TOTAL_LICENSES] => 1
[DENIED_LICENSES] => 0
)
[1] => Array
(
[NAME] => FEMFAT
[VERSION] => 5.1
[VENDOR] => MAGNAECS
[END] => 2015-01-30
[USED_LICENSES] => 0
[TOTAL_LICENSES] => 1
[DENIED_LICENSES] => 0
)
从上面的数组我想要输出如下。如果name是相同的剩余值添加到第一个数组。
Array
(
[0] => Array
(
[NAME] => FEMFAT
[VERSION] => 5.1
[VENDOR] => MAGNAECS
[END] => 2015-01-30
[USED_LICENSES] => 1
[TOTAL_LICENSES] => 2
[DENIED_LICENSES] => 0
)
我尝试了什么:
$newArr = array();
foreach ($featureInfo as $val) {
$newArr[$val['NAME']] = $val;
}
$featureInfo = array_values($newArr);
答案 0 :(得分:2)
你几乎就在那里,当它尚未设置在新容器上时推送整个数组,如果已经设置,那么只需添加它们:
$newArr = [];
foreach($array as $value) {
if(!isset($newArr[$value['NAME']])) { // if this name is not yet inside, push it
$newArr[$value['NAME']] = $value;
} else { // if already inside then add
$newArr[$value['NAME']]['USED_LICENSES'] += $value['USED_LICENSES'];
$newArr[$value['NAME']]['TOTAL_LICENSES'] += $value['TOTAL_LICENSES'];
$newArr[$value['NAME']]['DENIED_LICENSES'] += $value['DENIED_LICENSES'];
}
}
// $newArr = array_values($newArr); // optional array reindex
答案 1 :(得分:0)
Ghost对array_reduce的回答:
// where $data is your original array
$final = array_values(array_reduce($data, function ($prev, $curr) {
if (isset($prev[$curr['NAME']])) {
$prev[$curr['NAME']]['USED_LICENSES'] += $curr['USED_LICENSES'];
$prev[$curr['NAME']]['TOTAL_LICENSES'] += $curr['TOTAL_LICENSES'];
$prev[$curr['NAME']]['DENIED_LICENSES'] += $curr['DENIED_LICENSES'];
} else {
$prev[$curr['NAME']] = $curr;
}
return $prev;
}, array()));