通过PHP中的自定义顺序重新排列对象数组 [英] Rearrange an array of objects by a custom order in PHP

查看:74
本文介绍了通过PHP中的自定义顺序重新排列对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何重新排列对象数组,如:

How would I re-order an array of objects like:

Array
(
    [0] => stdClass Object
        (
            [term_id] => 3
            [name] => Name
        )
    [1] => stdClass Object
        (
            [term_id] => 1
            [name] => Name2
        )
    [2] => stdClass Object
        (
            [term_id] => 5
            [name] => Name
        )
)

根据对象term_id,针对自定义定义的ID数组:

According to the objects term_id, against a custom defined array of ids:

$ order_by = array(5,3,1)

$order_by = array( 5,3,1 )

我现在使用的是下面的内容,但是我觉得我没有利用PHP具有的一些高级排序功能...谁能告诉我什么会更好?

What I'm using now is below, but I feel like I'm not taking advantage of some advanced sorting functions PHP has... Can anyone tell me what would work better?

$sorted_terms = array();
$order_by = array( 5,3,1 );

foreach( $order_by as $id ) {
    foreach ( $terms as $pos => $obj ) {
        if ( $obj->term_id == $id ) {
            $sorted_terms[] = $obj;
            break;
        }
    }
}

推荐答案

基本上,术语的排序顺序与相应ID的排序相同,后者恰好是 $ order_by 数组.因此,我们只需要翻转该数组以获取id到等级的映射,然后将其与自定义比较功能一起使用即可进行排序.

Basically, the rank of your terms in their sorted order is the same as the rank of their corresponding ids, which happens to be the array keys in the $order_by array. So we just need to flip that array to get the mapping of ids to ranks, and then sort using it with a custom comparison function.

这是一个应该起作用的简单代码段:

Here's a simple code snippet that should work:

<?php

   $skeys = array_flip($order_by);
   usort($terms,
             function($a,$b) use ($skeys){$a =  $skeys[$a->term_id]; $b = $skeys[$b->term_id]; return $a - $b;});

以上代码可在PHP 5.3或更高版本上使用.

The above code would work with PHP 5.3 or later.

与5.3之前的PHP相同:

Here's the same thing with pre 5.3 PHP:

 <?php

   $skeys = array_flip($order_by);
   function sfun($a,$b){
       global $skeys;
       $a =  $skeys[$a->term_id]; $b = $skeys[$b->term_id]; return $a - $b;
   }

   usort($terms, "sfun");

重要功能是:

这篇关于通过PHP中的自定义顺序重新排列对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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