<?php
$canonicalIds = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
];
$putContent = [
[
'id' => 'fifth',
'value' => 55,
],
[
'id' => 'second',
'value' => 22,
],
[
'id' => 'fourth',
'value' => 44,
],
[
'id' => null,
'value' => 7,
],
];
[$toCreate, $toUpdate] = array_reduce(
$putContent,
static function (array $carry, array $item) use ($canonicalIds): array {
[$toCreate, $toUpdate] = $carry;
if (null === $item['id']) {
$toCreate[] = $item;
} elseif (true === in_array($item['id'], $canonicalIds, true)) {
$toUpdate[$item['id']] = $item;
}
return [
$toCreate,
$toUpdate
];
},
[
[],
[]
]
);
$toDelete = array_diff($canonicalIds, array_keys($toUpdate));
var_dump($toCreate, $toUpdate, $toDelete);
- Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.27, 8.3.0 - 8.3.15, 8.4.1 - 8.4.2
- array(1) {
[0]=>
array(2) {
["id"]=>
NULL
["value"]=>
int(7)
}
}
array(3) {
["fifth"]=>
array(2) {
["id"]=>
string(5) "fifth"
["value"]=>
int(55)
}
["second"]=>
array(2) {
["id"]=>
string(6) "second"
["value"]=>
int(22)
}
["fourth"]=>
array(2) {
["id"]=>
string(6) "fourth"
["value"]=>
int(44)
}
}
array(3) {
[0]=>
string(5) "first"
[2]=>
string(5) "third"
[5]=>
string(5) "sixth"
}
preferences:
87.63 ms | 407 KiB | 5 Q