我有一个数组($排序),看起来像:
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 自己。
Alternatively you can get an implementation written in PHP by the author of array_column himself.
更多推荐
排序多维数组基于另一个数组
发布评论