我有这个输出:
array ( 0 => array ( 0 => 'Category 1', 1 => '475.00', ), 1 => array ( 0 => 'Category 1', 1 => '5.00', ), 2 => array ( 0 => 'Category 2', 1 => '18.00', ),...
可读版本:
Category 1 | 475.00
Category 1 | 5.00
Category 2 | 18.00
Category 3 | 5.00
如何合并重复的字符串并获得价格总和?我将在foreach中使用此输出。
(2) Category 1 | 480.00
(1) Category 2 | 18.00
(1) Category 3 | 5.00
答案 0 :(得分:1)
您可以使用array_reduce()
尝试这样的操作<?php
$array = array ( 0 => array ( 0 => 'Category 1', 1 => '475.00', ),
1 => array ( 0 => 'Category 1', 1 => '5.00', ),
2 => array ( 0 => 'Category 2', 1 => '18.00', ),
3 => array ( 0 => 'Category 3', 1 => '5.00', )
);
$final = array_reduce($array, function($result, $item) {
$result[$item[0]] += $item[1];
return $result;
}, ['Category 1'=>0,'Category 2'=>0,'Category 3'=>0]);
print '<pre>';
print_r($final);
print '</pre>';
?>