排序多维数组基于另一个数组

编程入门 行业动态 更新时间:2024-10-11 15:23:39
本文介绍了排序多维数组基于另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数组($排序),看起来像:

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.

更多推荐

排序多维数组基于另一个数组

本文发布于:2023-11-29 04:09:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645225.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   多维

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!