2016-07-25 87 views
0

我有以下php array对象:如何在PHP中使用对象元素对数组进行排序?

"requests": [ 
{   
    "id": 111, 
    "time: 123123123, 
    "data": "testc" 
},  
{     
    "id": 200 , 
    "time: 433123123, 
    "data": "testb" 
},  
{ 
    "id": 300 , 
    "time: 33123123, 
    "data": "testb" 
} 
] 

我想只有requests->time对它进行排序。怎么做?我不想按id排序。所有数据应按照time ASC排序。

+3

http://stackoverflow.com/questions/16306416/sort-php-multi-dimensional-array-based-on-key – sozkul

+1

使用[usort()](http://www.php.net/manual/en/ function.usort.php) –

+0

如果你从查询中获得这些数据,那么只使用'ORDER BY time ASC'。否则使用'usort()' –

回答

1

你必须与usort()

解决方案用自己的排序方法:

<?php 
function sortByTimeASC($a, $b) 
{ 
    if ($a->time == $b->time) { 
     return 0; 
    } 
    return ($a->time < $b->time) ? -1 : 1; 
} 

$a = json_decode('[{"id": 111,"time": 123123123,"data": "testc"},{ "id":200 ,"time":433123123,"data":"testb"},{"id":300,"time":33123123,"data":"testb"}]'); 

usort($a, "sortByTimeASC"); 
print_r($a); 
?> 

Live example

2

假设你有一个$requests变量,数组,下面应该工作

<?php 
    function cmp($a, $b) 
    { 
     return strcmp($a["time"],$b["time"]); 
    } 
    usort($requests, "cmp"); 

    //print for test 
    while (list($key, $value) = each($requests)) { 
     echo "\$requests[$key]: " . $value["time"] . "\n"; 
    } 

?> 
相关问题