简体   繁体   English

如何基于第二个数组对PHP数组进行排序?

[英]How to sort a PHP array based on a second array?

I have two simple arrays. 我有两个简单的数组。 One is an array of posts ($posts) and the other is an array of post ID's that should be on top of the stream, like they are featured ($featured). 一个是一系列帖子($ posts),另一个是一系列帖子ID,这些ID应该位于信息流的顶部,就像它们的特色($ featured)。 I am trying to find an efficient way to loop through them and if an ID is in both arrays, move it to the beginning of the $posts array, and the ones that are moved should be sorted ASC by $featured['order'], so for example, some posts ($posts): 我正在尝试找到一种有效的方法来遍历它们,并且如果两个数组中都存在ID,请将其移至$ posts数组的开头,并且所移动的ID应按$ featured ['order']进行ASC排序,例如,一些帖子($ posts):

Array
(
    [ab77] => Status_Update Object
        (
            [id] => ab77
            [title] => Status Update
         )

    [b4k7] => Status_Update Object
         (
             [id] => b4k7
             [title] => Status Update
         )
    [4d55] => Status_Update Object
         (
             [id] => 4d55
             [title] => Status Update
         )

    [13c5] => Status_Update Object
         (
             [id] => 13c5
             [title] => Status Update
          )

     [3aa2] => Status_Update Object
          (
              [id] => 3aa2
              [title] => Status Update
           )
)

and then some posts which should be featured ($featured): 然后是应该精选的一些帖子(精选):

Array
(
    [13c5] => Array
         (
             [id] => 13c5
             [order] => 1
         )

    [3a71] => Array
         (
             [id] => 3a71
             [order] => 2
         )

    [4d55] => Array
         (
             [id] => 4d55
             [order] => 3
         )

)

So the $posts array should end up sorted like this: 因此,$ posts数组应该最终像这样排序:

13c5 4d55 ab77 bk47 3aa2 13c5 4d55 ab77 bk47 3aa2

How do I do this without a bunch of slow loops? 没有一堆慢循环怎么办?

This should be doable with uksort() and closures : 这应该可以与uksort()闭包一起使用

uksort( $posts, function ( $a, $b ) use ( $featured ) {
    $fa = ( isset( $featured[$a] ) ? $featured[$a]['order'] : INF );
    $fb = ( isset( $featured[$b] ) ? $featured[$b]['order'] : INF );
    if ( $fa != $fb ) return ( $fa < $fb ? -1 : +1 );
    // could add a tie-breaker comparison here
    return 0;
} );

This is the messy answer I came up with works. 这是我想出的混乱答案。

$found, $not_found = array();

foreach ($posts as $key => $value) {
    if (array_key_exists($key, $featured)) {
        $found[$key] = $value;
    } else {
        $not_found[$key] = $value;
    }
}

usort($found, 'sort_by_order');

function sort_by_order ($a, $b) {
    return $a['order'] - $b['order'];
}

$new = array_merge($found, $not_found);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM