我正在從JSON讀取多維數組。然後我需要根據兩個參數進行排序,這個參數大概有三個深度。在PHP中使用多個條件對多維數組進行排序
我試過在array_multisort,但只能做一個級別相對應的時間。然後我根據我在stackoverflow上看到的幾個例子轉移到了usort,但它頑固地拒絕工作。
JSON:
[
{
"multiple parameters": "foobar",
"projects": [
{
"id": "00101",
"date": "9",
"time": "14:00",
"duration":"30"
},
{
"id": "EX001",
"date": "8",
"time": "13:30",
"duration":"15"
},
{
"id": "9A200",
"date": "10",
"time": "8:45",
"duration":"15"
},
{
"id": "EQ002",
"date": "8",
"time": "9:30",
"duration":"15"
}
]
}
]
PHP:
//read data from the json file
$theschedule = '/directory/path/schedule.json';
//read json file
if (file_exists ($theschedule)){
$contents = utf8_encode(file_get_contents($theschedule));
$Schedule= json_decode($contents, true);
//Sort array
usort($Schedule[0]['projects'], 'order_by_date_time');
function order_by_date_time($a, $b)
{
if ($a['date'] == $b['date'])
{
// date is the same, sort by time
if ($a['time'] == $b['time']) return 0;
return $a['time'] == 'y' ? -1 : 1;
}
// sort the date first:
return $a['date'] < $b['date'] ? 1 : -1;
}
每次會議都有日期和時間 - 我需要按日期排序,然後時間,來填充會議日程頁面。
我讀過很多很多的stackoverflow文章。最有用的是 Sort multidimensional array by multiple criteria
Sort an associative array in php with multiple condition(以下簡稱「order_by_date_time」功能的源)
我在http://www.php.net/manual/en/function.usort.php閱讀usort PHP手冊(和許多其他數組排序功能)。
我也驗證了JSON與JSONLint,所以我不認爲這是問題 - 但如果這可能是問題,我可以改變它。
我知道相關問題都已經在這裏提出之前 - 我看了這麼多的職位,並嘗試了許多建議的答案。但是,我的代碼中缺少一些內容,我無法看到。
strtotime看起來很有希望,但它仍然沒有排序任何東西。完全困惑。我使用的是5.3.3版本;想不到任何原因,只是沒有排序。 – user2208757
@ user2208757添加了一個鏈接以顯示它的工作原理。 – Orangepill
我不知道小提琴有什麼魔力,但它有效。有用!!!!!很高興。非常困惑,因爲我正在比較兩組相同的代碼,其中一組工作,另一組不工作,我會最終找到差異。但在此期間,快樂的舞蹈。 :) 謝謝!! – user2208757