I am having two arrays in php 7.4.16
$data_one = array(
['id' => 491, 'default' => false],
['id' => 492, 'default' => false],
['id' => 493, 'default' => true],
);
and
$data_two = array(
['id' => 491, 'default' => false],
['id' => 492, 'default' => true],
['id' => 493, 'default' => false],
['id' => 494, 'default' => false],
);
I am using the spread operator:
$data_one = [...$data_two];
is adding the missing array with id 494 to $data_one .... but also is overwriting the value for "default" in the $data_one. (in the first array with id 492 the default will become true, and id 493 will become false)
How can I add the new entries from $data_two to $data_one but keep the original values ("default") from $data_one ?
** UPDATE **
the final array should look like this
$data_one = array(
['id' => 491, 'default' => false],
['id' => 492, 'default' => false],
['id' => 493, 'default' => true],
['id' => 494, 'default' => false],
);
CodePudding user response:
Loop through the elements in $data_two
. Check if its id
already exists in $data_one
. If not, add it.
$ids = array_column($data_one, 'id');
foreach ($data_two as $item) {
if (!in_array($item['id'], $ids)) {
$data_one[] = $item;
}
}
CodePudding user response:
Use the spread operator (array_merge()
on array values only, surrogate for array_values()
) with the array union operator over the id-indexed $data_one
and $data_two
arrays with $data_two
being on the right-hand side:
$id = 'id';
$idx = static fn(array $data) => array_column($data, null, $id);
$result = [
... $idx($data_one)
$idx($data_two)
];
Only the values of new entities (identity by their id) are appended.
All id
s should be integers.
If you're not interested in the resulting array keys, you can also keep them:
$id = 'id';
$idx = static fn(array $data) => array_column($data, null, $id);
$result = $idx($data_one)
$idx($data_two)
;
And a more generic PHP code example on 3v4l.org: https://3v4l.org/2Lk8R (PHP 5.5 variant).