0

我的代码如下

$results = array();
$results[] = json_decode("json api response url", true);
$results[] = json_decode("json api response url 2", true);
$results[] = json_decode("json api response url 3", true);
foreach($results as $result) {
     $decoded = $result['Info'];
     usort($decoded, function($a, $b) { return $a['price'] > $b['price'] ? 1 : -1; });
     foreach($decoded as $row) {
         echo $row['price'];
     } 
}

JSON数组返回如下

["Info"]=>
[0]=>
array(13) {
  ["price"]=>  
    int(3000)
} 
[1]=>
array(13) {
  ["price"]=>
     int(5000)

usort为每个json_decode响应而不是所有响应都做一个,他们是否可以解决这个问题?

4

3 回答 3

2

您正在对数组中的每个项目执行排序。在遍历结果之前尝试进行排序。我不知道这是否可行,但它应该为您指明正确的方向。

$results = array();
$results[] = json_decode("json api response url", true);
$results[] = json_decode("json api response url 2", true);
$results[] = json_decode("json api response url 3", true);

usort($results, function($a, $b) {
  return $a['Info']['price'] > $b['Info']['price'] ? 1 : -1;
});

foreach($results as $result) {
   // do your looped stuff
}
于 2013-03-25T15:24:43.660 回答
1

我认为您想要做的是连接所有 JSON 响应并将它们放在一起,而不是在 results[]; 中创建 3 个不同的数组元素;查看array_merge():

$result = array();
$arr1 = json_decode("json api response url", true);
$arr2 = json_decode("json api response url 2", true);
$arr3 = json_decode("json api response url 3", true);

$result = array_merge($arr1['Info'], $arr2['Info'], $arr3['Info']);

$decoded = $result;
usort($decoded, function($a, $b) { return $a['price'] > $b['price'] ? 1 : -1; });
foreach($decoded as $row) {
  echo $row['price'];
} 
于 2013-03-25T15:12:57.740 回答
0
$results = array();
$results[] = json_decode("json api response url", true);
$results[] = json_decode("json api response url 2", true);
$results[] = json_decode("json api response url 3", true);

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

usort($results, "cmp");

foreach($results as $row) {
   echo $row['price'];
}
于 2013-03-25T15:34:24.870 回答