2014-05-19 243 views
0

我有一個數組我想按照優先級DESC的值排序。多維數組按鍵值排序PHP

"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 
    } 

] 

我用這個代碼,但它不是work.Its總是給結果=「空」

我使用的代碼

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") 
      ); 

我如何排序這個數組由值了「優先級「DESC

+1

'aasort'不返回任何東西。 –

回答

1

這將做到這一點,您將需要先提取數組並解碼它。

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); 
+2

你實際上想'返回$ a ['priority'] - $ b ['priority'];'。 –

+0

@RocketHazmat謝謝 – Flosculus

0

PHP> = 5.5.0

$array = json_decode($json, true); 
array_multisort(array_column($array['result'], 'priority'), 
    SORT_DESC, $array['result']);