0

I have an array i want to sort it by value of priority DESC.

"status":"OK",
"baseurl":"http://www.test.com",
"pictureurl":"http://www.test.com",
"result":[
    {
        "videoid":"60",
        "username":"1556495708",
        "submittime":"1400112000",
        "videotitle":"Test Video",
        "videodescription":"Test Video Description",
        "priority":12
    },
    {
        "videoid":"61",
        "username":"1556495708",
        "submittime":"1400151306",
        "videotitle":"Test Video",
        "videodescription":"Test Video Description",
        "priority":20
    }

]

I use this code but Its not work.Its always give result="null"

my Used Code

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}



    $output = array(
                'status' => $status,
                'baseurl' =>$baseURL,
                'pictureurl' =>$imagebaseURL,
                'result' => aasort($info,"priority")
            );

How can I sort this array by the value of the "priority" DESC

user3533255
  • 45
  • 2
  • 8

2 Answers2

1

This will do it, you will need to extract the array and decode it first however.

echo '<pre>';

$json = '
[
    {
        "videoid":"60",
        "username":"1556495708",
        "submittime":"1400112000",
        "videotitle":"Test Video",
        "videodescription":"Test Video Description",
        "priority":12
    },
    {
        "videoid":"61",
        "username":"1556495708",
        "submittime":"1400151306",
        "videotitle":"Test Video",
        "videodescription":"Test Video Description",
        "priority":20
    }

]';
$array = json_decode($json, true);

function do_sort($a, $b) {
    return $b['priority'] - $a['priority'];
}

usort($array, 'do_sort');

print_r($array);
Flosculus
  • 6,880
  • 3
  • 18
  • 42
0

PHP >= 5.5.0:

$array = json_decode($json, true);
array_multisort(array_column($array['result'], 'priority'),
    SORT_DESC, $array['result']);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87