1

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!

Frank Lucas
  • 551
  • 3
  • 11
  • 25
  • Did you ever try to search before posting? There are dozens of similar questions available in SO – Thamilhan Jan 05 '17 at 09:27
  • @Thamilan Yes I did but I can't find anything to sort on a specific key or put an elemt at the front of an array – Frank Lucas Jan 05 '17 at 09:28
  • Did you try these http://stackoverflow.com/a/4022355/5447994 ? http://stackoverflow.com/a/2804735/5447994 ? – Thamilhan Jan 05 '17 at 09:31
  • @Thamilan Yes but looks very complicated – Frank Lucas Jan 05 '17 at 09:35
  • Complicated or not @FrankLucas - those answers are going to solve your issue. In fact, looking at that first one, it's not really that complicated. [Look at the PHP.net docs for usort](http://php.net/manual/en/function.usort.php) and you should be able to figure it out if you actually have a go. Then, if you're stuck come back with your code and we can help. – Tom Jan 05 '17 at 09:42

1 Answers1

0

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

lazyCoder
  • 2,544
  • 3
  • 22
  • 41