0
我正在使用php5和mysql 5.6PHP:無法發表評論樹
我的任務是創建一個評論樹並將其全部視爲json。每個評論都有其所屬的評論的ID和ID,名爲rootId。 我從日期時間的數據庫中獲得了評論。
我所做的解決方案僅以降序工作。按升序排列樹形不正確。而事情是我需要按照升序顯示評論。
如果有人這樣之前遇到,請幫我解決這個問題
這裏是我的代碼:
// $result - associative array with all comments
for ($i = 0; $i < $arrayLength; ++$i){
if ($result[$i]['rootid'] != 0){
for ($j = 0; $j < $arrayLength; ++$j){
if ($result[$j]['id'] == $result[$i]['rootid']){
if ($result[$j]['child'] != 0){ // the case when there's at least 1 child
$result[$j]['child'][] = $result[$i];
}
else {
$result[$j]['child'] = $result[$i]; // case when no children
}
break;
}
}
unset($result[$i]);
}
}
這是什麼,我得到一個小例子。
[
{
"id": "652061",
"rootid": "0",
"date_add": "2017-03-18 22:40:31",
"child": [
{
"id": "652063",
"rootid": "652061",
"date_add": "2017-03-18 22:58:54",
"child": [
{
"id": "652072",
"rootid": "652063",
"date_add": "2017-03-18 23:13:54",
"child": [
{
"id": "652118",
"rootid": "652072",
"date_add": "2017-03-19 08:03:36",
"child": []
}
]
}
]
}
]
},
{
"id": "651999",
"rootid": "0",
"date_add": "2017-03-18 19:26:10",
"child": [
{
"id": "652104",
"rootid": "651999",
"date_add": "2017-03-19 01:17:32",
"child": []
},
{
"id": "652066",
"rootid": "651999",
"date_add": "2017-03-18 23:02:26",
"child": []
}
]
} ]
但如果我更改SQL請求
ORDER BY datetime ASC
不正確的方式樹的形式,只有少數意見認爲他們的父母,不是所有的
什麼意思是「降序」和「升序」的順序?在你的具體情況下,它會更好地工作,首先由rootId命令,然後是時間戳? –
如果您提供結果數組的小示例,當前輸出和預期輸出,它會有所幫助。 – k0pernikus
請閱讀:https://stackoverflow.com/help/mcve – k0pernikus