dongxianrang9269 2017-02-17 08:09
浏览 44
已采纳

array_push或array_unshift多行到同一个数组PHP的顶部

I have an array:

[0] => Array
    (
        [Id] => 1
        [Order] => 1
        [ContentGroupId] => 10
        [ContentGroupIsNew] => 0
 )

[1] => Array
    (
        [Id] => 2
        [Order] => 2
        [ContentGroupId] => 11
        [ContentGroupIsNew] => 0
 )
[2] => Array
    (
        [Id] => 3
        [Order] => 3
        [ContentGroupId] => 12
        [ContentGroupIsNew] => 1
 )
[3] => Array
    (
        [Id] => 4
        [Order] => 4
        [ContentGroupId] => 13
        [ContentGroupIsNew] => 1
 )
[4] => Array
    (
        [Id] => 5
        [Order] => 5
        [ContentGroupId] => 14
        [ContentGroupIsNew] => 0
 )

The default order is by [Order] I want to re-sort this array so that it orders by [ContentGroupIsNew] = 1 at the top (if any exist, in this sample 2 do exist), but keep the existing order of the remainder of elements.

If I use a usort function, I can get the [ContentGroupIsNew] = 1 but then the remainder of elements seems to get randomly ordered and not keep true to the original [Order] value.

So the final result should look like this:

[0] => Array
    (
        [Id] => 3
        [Order] => 3
        [ContentGroupId] => 12
        [ContentGroupIsNew] => 1
 )

[1] => Array
    (
        [Id] => 4
        [Order] => 4
        [ContentGroupId] => 13
        [ContentGroupIsNew] => 1
 )
[2] => Array
    (
        [Id] => 1
        [Order] => 1
        [ContentGroupId] => 10
        [ContentGroupIsNew] => 0
 )
[3] => Array
    (
        [Id] => 2
        [Order] => 2
        [ContentGroupId] => 11
        [ContentGroupIsNew] => 0
 )
[4] => Array
    (
        [Id] => 5
        [Order] => 5
        [ContentGroupId] => 14
        [ContentGroupIsNew] => 0
 )

PHP code:

function sort_array($b, $a) {
  return $a['ContentGroupIsNew'] - $b['ContentGroupIsNew'];
}

usort($array, 'sort_array');
  • 写回答

2条回答 默认 最新

  • dongzh1988 2017-02-17 08:34
    关注
    foreach ($data as $key => $row) {
        $return_fare[$key]  = $row['ContentGroupIsNew'];
        $one_way_fare[$key] = $row['Id'];
    }
    
    
    array_multisort($return_fare, SORT_DESC, $one_way_fare, SORT_ASC, $data);
    print_r($data);
    

    found this solution here : PHP sort array by two field values

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?