I have one array ($sort)
that looks like:
[1]=>16701
[2]=>16861
[3]=>16706
And an array ($images)
, which looks like:
[0]=>
array(4) {
["href"]=> string(35) "mystring"
["url"]=> string(67) "mystring2"
["didascalia"]=> string(29) "mystring3"
["id"]=> 16861
}
[1]=>
array(4) {
["href"]=> string(35) "mystring"
["url"]=> string(70) "mystring2"
["didascalia"]=> string(37) "mystring3"
["id"]=> 16706
}
[2]=>
array(4) {
["href"]=> string(35) "mystring"
["url"]=> string(66) "mystring2"
["didascalia"]=> string(24) "mystring3"
["id"]=> 16701
}
I need to sort $images
, based on value "id"
, using $sort
.
So my result should be
[0]=>
array(4) {
["href"]=> string(35) "mystring"
["url"]=> string(66) "mystring2"
["didascalia"]=> string(24) "mystring3"
["id"]=> 16701
}
[1]=>
array(4) {
["href"]=> string(35) "mystring"
["url"]=> string(67) "mystring2"
["didascalia"]=> string(29) "mystring3"
["id"]=> 16861
}
[2]=>
array(4) {
["href"]=> string(35) "mystring"
["url"]=> string(70) "mystring2"
["didascalia"]=> string(37) "mystring3"
["id"]=> 16706
}
How can I do it? I tried using multisort, array_map but without success.
Since you already have the ids in the desired sort order, the only barrier to sorting $images
efficiently is the inability to immediately fetch an image given its id. So let's fix that by reindexing $images
to use the id as the array key using array_column
(don't get thrown by the name, it can also be used for reindexing):
// array_column is only available in PHP 5.5+
$images = array_column($images, null, 'id');
After this it's trivial to get a sorted array:
$sortedImages = [];
foreach ($sort as $id) {
$sortedImages[] = $images[$id];
}
For PHP < 5.5 you can substitute the array_column
reindexing with this:
$imageIds = array_map(function($i) { return $i['id']; }, $images);
$images = array_combine($imageIds, $images);
Alternatively you can get an implementation written in PHP by the author of array_column
himself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With