dsjbest2014 2017-01-05 09:21
浏览 43

PHP按特定键排序数组[重复]

This question already has an answer here:

I have an array that looks like this:

"lines":[
 {"value":1,"id":0},
 {"value":10,"id":1}
]

My goal is to always get the one with value: 10 as first so I want to sort it with ksort maybe but I am not sure

This is my goal:

"lines":[
 {"value":10,"id":1},
 {"value":1,"id":0}
]

Anyone who can help many thanks!

</div>
  • 写回答

1条回答 默认 最新

  • dongtan9066 2017-01-05 14:16
    关注

    @Frank Lucas If you want to order a multidimensional array by any key so you can you usort() function

    If you want to sort you array by "value" index in descending order so try the below code and understand it

    <?php
        $lines = array(array("value"=>1,"id"=>0), array("value"=>10,"id"=>1));
        function order($a, $b){
            if ($a["value"] == $b["value"]) {  //here pass your index name
                return 0;
            }
            return ($a["value"] > $b["value"]) ? -1 : 1;    // this your key "value" will be in descending order as  requirement
            //but if you want to change this order from descending to Ascending order so just change the -1 and 1 place in above condition 
        }
        usort($lines,"order");
        print_r($lines);
    ?>
    

    It will solve your problem (y)

    评论

报告相同问题?