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条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。