排序多维数组基于另一个数组 [英] Sort multidimensional array based on another array
问题描述
我有一个数组($排序)
,看起来像:
I have one array ($sort)
that looks like:
[1]=>16701
[2]=>16861
[3]=>16706
和数组($图片)
,它看起来像:
[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
}
我该怎么办呢?
我试着用multisort,array_map但没有成功。
How can I do it? I tried using multisort, array_map but without success.
推荐答案
既然你已经拥有所需的排序顺序的ID,唯一的障碍排序 $图像
高效是不能立即取定其ID的图像。因此,让我们解决这个问题通过重新编制 $图像
使用的 array_column
(不要被名称抛出,也可用于重建索引):
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];
}
有关PHP< 5.5可以替代与此 array_column
重新索引:
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);
另外你可以得到由 array_column $ C $的作者用PHP编写的 实现C>自己。
Alternatively you can get an implementation written in PHP by the author of array_column
himself.
这篇关于排序多维数组基于另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!