0

I have two multidimensional arrays in PHP, the first one being

[0] => [
'id' => 123,
'name' => 'John'
],

[1] => [
'id' => 456,
'name' => 'Anna'
],

[2] => [
'id' => 789,
'name' => 'Mario'
]

And the second one is like this:

[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:

[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!

2 Answers 2

1

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.

<?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:

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,
  ),
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, your solution worked perfectly fine. I still need to sort by position, is there any way to do this during the array creation or I need to sort it after the creation?
Oh forgive me, I didn't read the sort, have added a post sort.
0

Many problems like this can be solved also with just a few lines of code using this extern PHP class tableArray.

$result = tableArray::create($names)
  ->leftJoinOn($positions,'t2','id','id')
  ->select('id,name,t2.position AS position')
  ->orderBy('position ASC')
  ->fetchAll()
;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.