通过预定义的值映射对对象数组进行排序 [英] Sorting Arrays of objects by predefined map of values

查看:94
本文介绍了通过预定义的值映射对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

$inputArray = Array(
    [0] => stdClass Object (
        [id] => 8
    )

    [1] => stdClass Object (
        [id] => 7
    )

    [2] => stdClass Object (
        [id] => 5
    )
)

$sortingArray = [5,8,1]

我正在寻找一种通过ID值映射"对输入数组进行排序的有效方法..预期的输出应为$ inputArray重新排序,以便第3个项目为第一,第一个项目为第二,依此类推. >

谢谢!

解决方案

在这里我使用了一些东西,主要是我将排序数组用作array_replace()的目标,而我使用了array_column()索引对象(需要PHP 7.0+才能使用对象)...

$input = array_column($inputArray, null, "id");   
$sort = array_fill_keys($sortingArray, null);
$output = array_filter(array_replace($sort, $input));

array_filter()将删除不在输入数组中但在排序数组中的所有元素.使用array_fill_keys()代替array_flip(),以便我可以设置一个空值,以使过滤器正常工作.

I have the following Arrays:

$inputArray = Array(
    [0] => stdClass Object (
        [id] => 8
    )

    [1] => stdClass Object (
        [id] => 7
    )

    [2] => stdClass Object (
        [id] => 5
    )
)

$sortingArray = [5,8,1]

I'm looking an efficient way to sort the input array by the id "map of values".. expected output should be $inputArray reordered so that 3rd item would be first, first item would be 2nd etc.

thanks!

解决方案

I've used a few things here, the main thing is that I use the sorting array as a target for an array_replace() and I use array_column() to index the objects by (this needs PHP 7.0+ to work with objects)...

$input = array_column($inputArray, null, "id");   
$sort = array_fill_keys($sortingArray, null);
$output = array_filter(array_replace($sort, $input));

The array_filter() will remove any elements which aren't in the input array but in the sorting array. The array_fill_keys() is used instead of array_flip() so that I can set a null value, which allows the filter to work.

这篇关于通过预定义的值映射对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆