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!

5
  • Did you ever try to search before posting? There are dozens of similar questions available in SO Commented Jan 5, 2017 at 9: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 Commented Jan 5, 2017 at 9:28
  • Did you try these stackoverflow.com/a/4022355/5447994 ? stackoverflow.com/a/2804735/5447994 ? Commented Jan 5, 2017 at 9:31
  • @Thamilan Yes but looks very complicated Commented Jan 5, 2017 at 9: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 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. Commented Jan 5, 2017 at 9:42

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.