gpt4 book ai didi

php - 如何在PHP中合并具有相同键和不同值的数组?

转载 作者:行者123 更新时间:2023-12-04 06:38:39 24 4
gpt4 key购买 nike

我有与这些类似的数组:

0 => Array ( [0] => Finance / Shopping / Food, [1] => 47 )            
1 => Array ( [0] => Finance / Shopping / Food, [1] => 25 )
2 => Array ( [0] => Finance / Shopping / Electronic, [1] => 190 )

我需要创建一个数组,其中 [0] 作为键,[1] 作为值。
棘手的部分是,如果 [0] 相同,则会将 [1] 添加到现有值。

所以我想要的结果是:
array ([Finance / Shopping / Food]=> 72, [Finance / Shopping / Electronic] => 190);

谢谢

最佳答案

// array array_merge_values($base[, $merge[, ...]])
// Combines multiple array values based on key
// (adding them together instead of the native array_merge using append)
//
// $base - array to start off with
// $merge[...] - additional array(s) to include (and add their values) on to the base
function array_merge_values()
{
$args = func_get_args();

$result = $args[0];
for ($_ = 1; $_ < count($args); $_++)
foreach ($args[$_] as $key => $value)
{
if (array_key_exists($key,$result))
$result[$key] += $value;
else
$result[$key] = $value;
}
return $result;
}

$array1 = Array('foo' => 5, 'bar' => 10, 'foobar' => 15);
$array2 = Array('foo' => 20, 'foohbah' => 25);
$array3 = Array( 'bar' => 30);
var_dump(array_merge_values($array1,$array2,$array3));

结果:
array(4) {
["foo"]=>
int(25)
["bar"]=>
int(40)
["foobar"]=>
int(15)
["foohbah"]=>
int(25)
}

那是你要找的?

关于php - 如何在PHP中合并具有相同键和不同值的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com