假设我有两个数组:
1:
Array
(
[0] => stdClass Object
(
[uuid] => 12e3b273-ef84-4960-9f81-16cc35e69a58
[sum] => 10
)
[1] => stdClass Object
(
[uuid] => 345265aa-5f85-405d-b256-9f2cc706d222
[sum] => 20
)
[2] => stdClass Object
(
[uuid] => 8650b97e-f7c0-4d4c-a065-a082bd4fdbce
[sum] => 30
)
)
2:
Array
(
[0] => stdClass Object
(
[uuid] => 6be4da35-f0d0-4b24-99ed-ad06b95354ce
[sum] => 200
)
[1] => stdClass Object
(
[uuid] => 8650b97e-f7c0-4d4c-a065-a082bd4fdbce
[sum] => 100
)
)
如果第一个数组中存在“sum”,如何合并它们和求和值?
最终数组应如下所示:
Array
(
[0] => stdClass Object
(
[uuid] => 12e3b273-ef84-4960-9f81-16cc35e69a58
[sum] => 10
)
[1] => stdClass Object
(
[uuid] => 345265aa-5f85-405d-b256-9f2cc706d222
[sum] => 20
)
[2] => stdClass Object
(
[uuid] => 8650b97e-f7c0-4d4c-a065-a082bd4fdbce
[sum] => 130 (100 + 30)
)
[3] => stdClass Object (added because it doesn´t excist in first array)
(
[uuid] => 6be4da35-f0d0-4b24-99ed-ad06b95354ce
[sum] => 200
)
)
不知道从哪里开始。
迭代数组并检查值是一项简单的任务。我编写了两个简单的函数来帮助解决这个问题。第一个检查第一个数组并返回具有相同 UUID 的对象的索引。
function getIndex(array $array1, stdClass $object): ?string
{
foreach ($array1 as $key => $value) {
if ($value->uuid === $object->uuid) {
return $key;
}
}
return null;
}
第二个函数是对这些数组中的对象进行合并和求和的算法。请注意,此函数会改变第一个数组。如果这不是预期的行为,您可以将结果存储在函数中创建的另一个数组中并返回该数组,而不是改变第一个数组。
function mergeAndSum(array &$array1, array $array2): void
{
foreach ($array2 as $object) {
$key = getIndex($array1, $object);
if ($key !== null) {
$array1[$key]->sum += $object->sum;
} else {
$array1[] = $object;
}
}
}
当像这样调用这些函数时,它会产生你想要的输出。
$array1 = [
(object) [
'uuid' => '12e3b273-ef84-4960-9f81-16cc35e69a58',
'sum' => 10
],
(object) [
'uuid' => '345265aa-5f85-405d-b256-9f2cc706d222',
'sum' => 20
],
(object) [
'uuid' => '8650b97e-f7c0-4d4c-a065-a082bd4fdbce',
'sum' => 30
],
];
$array2 = [
(object) [
'uuid' => '6be4da35-f0d0-4b24-99ed-ad06b95354ce',
'sum' => 200,
],
(object) [
'uuid' => '8650b97e-f7c0-4d4c-a065-a082bd4fdbce',
'sum' => 100,
],
];
mergeAndSum($array1, $array2);
print_r($array1);
Array
(
[0] => stdClass Object
(
[uuid] => 12e3b273-ef84-4960-9f81-16cc35e69a58
[sum] => 10
)
[1] => stdClass Object
(
[uuid] => 345265aa-5f85-405d-b256-9f2cc706d222
[sum] => 20
)
[2] => stdClass Object
(
[uuid] => 8650b97e-f7c0-4d4c-a065-a082bd4fdbce
[sum] => 130
)
[3] => stdClass Object
(
[uuid] => 6be4da35-f0d0-4b24-99ed-ad06b95354ce
[sum] => 200
)
)
只是一个免责声明 - 如果您尝试对大量这些对象求和,该算法可能会很慢。如果对象是唯一的,您可以通过 UUID 在关联数组中对它们进行索引,而不是在
getIndex
中迭代整个数组,您可以使用 isset
或 array_key_exists
检查元素是否在数组中。