-2

i am having a 2-dimensional array $a like this:

Array (
 [1] => Array ( 
 [id] => 19 
 [name] => SomeName 
),
[2] => Array ( 
 [id] => 23 
 [name] => AnotherName 
),
[3] => Array ( 
 [id] => 45 
 [name] => OneMoreName 
) 
)

And the second array $b like this:

Array (  
[0] => 45 
[1] => 23 
[2] => 19 
)

The values of 2nd array are id's from first array. The order of elements is right in 2nd array, but is not right in 1st. So, i want to re-order elements in 1st array to have finally:

Array (
 [1] => Array ( 
 [id] => 45 
 [name] => OneMoreName 
),
[2] => Array ( 
 [id] => 23 
 [name] => AnotherName 
),
[3] => Array ( 
 [id] => 19
 [name] => SomeName 
) 
)

Of course, the number of elements can be more than 3, but in both arrays it is always the same. What standart php function or what approach can i use to do this?

0

2 Answers 2

0

You could use some array_walk function, but to be more understandable, i would use a specific algorithm:

    $array1 = [
        ['id' => 19, 'name' => 'name19'],
        ['id' => 23, 'name' => 'name23'],
        ['id' => 45, 'name' => 'name45'],
    ];
    $array2 = [45, 23, 19];
    $newArray1 = [];
    
    foreach ($array1 as $data){
        // Get the array key from array2 with strict comparison value
        $newKey = array_search($data['id'], $array2, true);
        // Set it in a new array temporary
        $newArray1[$newKey] = $data;
    }
    $array1 = $newArray1;

This way is quite short and easily understandable by someone else

Sign up to request clarification or add additional context in comments.

2 Comments

this is what i need, just used array_search($data['id'], $array2, false); instead of array_search($data['id'], $array2, true); in my case, thanks a lot!
If you liked the solution, please upvote it and/or flag it as solved :)
0

One simple way:

$result = array_merge(array_flip($b), array_column($a, null, 'id'));
  • Index $a on the id and flip $b to get the values as the index
  • Merge the existing array into the ordered one, which will replace in the proper order

If you need to re-index then use array_values:

$result = array_values(array_merge(array_flip($b), array_column($a, null, 'id')));

I didn't test it but you could probably use array_intersect_key instead of array_merge.

1 Comment

...this also works! Fantastic!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.