2013-03-25 34 views
0
後不工作

我的代碼如下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); 
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

從循環中刪除它。 – str 2013-03-25 15:11:07

+0

在排序之前將三個數據數組合併成一個數組。 – CBroe 2013-03-25 15:11:31

+0

無關:'json_decode(「json api response url」),true);'那裏有太多的右括號(還有其他兩行) – scones 2013-03-25 15:12:45

回答

1

我想你想要做的是連接所有的JSON響應並將它們放在一起,而不是在結果[]中創建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']; 
} 
+0

請舉個小例子嗎? – 2013-03-25 15:21:48

+0

看到我上面的編輯 – Husman 2013-03-25 16:18:44

+0

仍然不起作用,出於某種原因只處理'$ arr3' – 2013-03-25 16:28:16

2

您在數組中的每一項執行usort。嘗試在循環播放結果之前先執行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 
} 
+0

仍然沒有工作,它只是產生相同的效果 – 2013-03-25 15:30:56

+0

@任何人檢查json_decode語句上的右括號的數量。你有太多。 – War10ck 2013-03-25 16:23:33

+0

不知道他們來自哪裏,修復。 – 2013-03-26 09:46:28

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']; 
} 
+0

產生與我原來的一樣,謝謝 – 2013-03-25 15:39:02