我的代码如下
$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
而不是所有这些响应,他们是否可以解决这个问题?
答案 0 :(得分:2)
您正在对阵列中的每个项目执行一次操作。在循环结果之前尝试执行usort。我不知道这是否有效,但它应该指向正确的方向。
$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
}
答案 1 :(得分: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'];
}
答案 2 :(得分: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'];
}