我有一个多维数组。
当数组中的第一个和第二个字符串都出现多次时,我需要一种方法来计算总值。
所以例如: 金属金属= 22 Black Toscano = 26
等...
有什么想法吗?
[0] => Array
(
[0] => Array
(
[0] => Black
[1] => Toscano
[2] => 14
)
[1] => Array
(
[0] => Gold
[1] => Metallic
[2] => 10
)
)
[1] => Array
(
[0] => Array
(
[0] => Gold
[1] => Metallic
[2] => 12
)
[1] => Array
(
[0] => Black
[1] => Toscano
[2] => 12
)
)
答案 0 :(得分:1)
这只是解决了数据结构的问题,因此您必须确保在实践中每两项都会得到一个数字。希望你能从中学到一些东西:)
$products = array(
array(
array("Black", "Toscano", 14),
array("Gold", "Metallic", 10)
),
array(
array("Black", "Toscano", 12),
array("Gold", "Metallic", 12)
),
);
$accumulated = array();
$key = "";
$callback = function($item, $index) use(&$key, &$accumulated) {
if($index != 2) {
$key .= $item;
} else {
if(!array_key_exists($key, $accumulated)) {
$accumulated[$key] = 0;
}
$accumulated[$key] += $item;
$key = "";
}
};
array_walk_recursive($products, $callback);
var_dump($accumulated);
答案 1 :(得分:0)
应该是循环数据并存储和数组的简单情况。这是使用带键的散列作为与分隔符标记值连接的对的一种可能性。
$separator = "||"; //take care to choose something that doesn't pop up in your data here
//$data = example data;
$pairs = array();
foreach ($data as $val) {
foreach ($val as $pair) {
$str = $pair[0] . $separator . $pair[1];
if (array_key_exists($str, $pairs))
$pairs[$str] += $pair[2];
else
$pairs[$str] = $pair[2];
}
}
print_r($pairs);
output:
["Black||Toscano"] => 26,
["Gold||Metallic"] => 22
此时可以轻松检索数据
foreach ($pairs as $str => $sum) {
$str = explode($separator, $str);
echo $str[0] . ", " . $str[1] . ": " . $sum;
}