已知表t1
id txt parent -------------------------- 1 上山打老虎 0 2 一二三四五 0 3 老虎不在家 1 4 啦啦啦啦啦 1 5 啊啊啊啊啊 2 6 嗯嗯恩恩恩 0 . . .
希望通過一次查詢
mysql_query("SELECT id,txt,parent FROM t1 ORDER BY id DESC")
經過php對資料的重新排列
這裡的代碼應該怎麼寫???
得到如下結構的資料
這個過程中的PHP處理代碼或者演算法應該怎麼寫?求指點。
回複內容:
已知表t1
id txt parent -------------------------- 1 上山打老虎 0 2 一二三四五 0 3 老虎不在家 1 4 啦啦啦啦啦 1 5 啊啊啊啊啊 2 6 嗯嗯恩恩恩 0 . . .
希望通過一次查詢
mysql_query("SELECT id,txt,parent FROM t1 ORDER BY id DESC")
經過php對資料的重新排列
這裡的代碼應該怎麼寫???
得到如下結構的資料
這個過程中的PHP處理代碼或者演算法應該怎麼寫?求指點。
Array ( [1] => Web Server [3] => Nginx [4] => Apache ) [2] => Array ( [2] => Database [5] => MySQL ) [6] => Array ( [6] => Browser ))
Code
/** * 無限子級遞迴迴圈 * @param [type] $data [description] * @param integer $pid [description] * @return [type] [description] */function unlimitedForChild ($data, $pid = 0) { $array = array(); foreach ($data as $value) { if ($value['parent'] == $pid) { $value['child'] = unlimitedForChild($data, $value['id']); $array[] = $value; } } return $array;}$data = array( array( 'id' => 1, 'txt' => '上山打老虎', 'parent' => 0 ), array( 'id' => 2, 'txt' => '一二三四五', 'parent' => 0 ), array( 'id' => 3, 'txt' => '老虎不在家', 'parent' => 1 ), array( 'id' => 4, 'txt' => '啦啦啦啦啦', 'parent' => 1 ), array( 'id' => 5, 'txt' => '啊啊啊啊啊', 'parent' => 2 ), array( 'id' => 6, 'txt' => '嗯嗯恩恩恩', 'parent' => 0 ), //附加3級 array( 'id' => 7, 'txt' => '第三級', 'parent' => 3 ),);$result = unlimitedForChild($data);echo '';print_r($result);echo '
';
Result
Array( [0] => Array ( [id] => 1 [txt] => 上山打老虎 [parent] => 0 [child] => Array ( [0] => Array ( [id] => 3 [txt] => 老虎不在家 [parent] => 1 [child] => Array ( [0] => Array ( [id] => 7 [txt] => 第三級 [parent] => 3 [child] => Array ( ) ) ) ) [1] => Array ( [id] => 4 [txt] => 啦啦啦啦啦 [parent] => 1 [child] => Array ( ) ) ) ) [1] => Array ( [id] => 2 [txt] => 一二三四五 [parent] => 0 [child] => Array ( [0] => Array ( [id] => 5 [txt] => 啊啊啊啊啊 [parent] => 2 [child] => Array ( ) ) ) ) [2] => Array ( [id] => 6 [txt] => 嗯嗯恩恩恩 [parent] => 0 [child] => Array ( ) ))
Array ( [name] => Web Server [sub] => Array ( [3] => Array ( [name] => Nginx ) [4] => Array ( [name] => Apache ) ) ) [2] => Array ( [name] => Database [sub] => Array ( [5] => Array ( [name] => MySQL ) ) ) [6] => Array ( [name] => Browser ))