I have two multidimensional arrays in PHP, the first one being
JavaScript
x
[0] => [
'id' => 123,
'name' => 'John'
],
[1] => [
'id' => 456,
'name' => 'Anna'
],
[2] => [
'id' => 789,
'name' => 'Mario'
]
And the second one is like this:
JavaScript
[0] => [
'id' => 123,
'position' => 3
],
[1] => [
'id' => 456,
'position' => 1
],
[2] => [
'id' => 789,
'position' => 2
]
I’m trying to get a union of the two arrays without replacing any value. I just want to add ‘position’ to the first array and also sort by this new value in the meantime, like this:
JavaScript
[0] => [
'id' => 456,
'name' => 'Anna',
'position' => 1
],
[1] => [
'id' => 789,
'name' => 'Mario',
'position' => 2
],
[2] => [
'id' => 123,
'name' => 'John',
'position' => 3
]
How can achieve this result in the most efficient way? Thank you!
Advertisement
Answer
You can build an array mapping ids to positions, and then loop through the a first of names (or a copy), and add the positions.
JavaScript
<?php
$names =
[
[
'id' => 123,
'name' => 'John'
],
[
'id' => 456,
'name' => 'Anna'
],
[
'id' => 789,
'name' => 'Mario'
]
];
$positions =
[
[
'id' => 123,
'position' => 3
],
[
'id' => 456,
'position' => 1
],
[
'id' => 789,
'position' => 2
]
];
$id_positions = array_column($positions, 'position', 'id');
$result = $names;
foreach($result as &$item) {
$item['position'] = $id_positions[$item['id']] ?? null;
}
unset($item);
uasort($result, function($a, $b) { return $a['position'] <=> $b['position']; });
var_export($result);
Output:
JavaScript
array (
0 =>
array (
'id' => 456,
'name' => 'Anna',
'position' => 1,
),
1 =>
array (
'id' => 789,
'name' => 'Mario',
'position' => 2,
),
2 =>
array (
'id' => 123,
'name' => 'John',
'position' => 3,
),
)