Re: [請益] 請問如何排序?很困難…

看板PHP作者 (桜町寧至)時間14年前 (2012/01/02 11:40), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/3 (看更多)
個人不太喜歡用遞迴,所以只用迴圈實現XD function custom_sort($source) { $depth = 0; $count = count($source); $parent = $child = $root = $output = array(); foreach($source as $key => $value) { if(isset($value['belong'][0])) { //我不知道在有母元素的時候order是否一定有,所以這樣寫 $child[$value['belong']][$key] = isset($value['order']) ? (int)$value['order'] : 0; } else { $root[] = $key; } } for($i=0; $i<$count; $i++) { if($depth != 0) { $output_key = array_shift($parent[$depth-1]); $output[$output_key] = $source[$output_key]; if(isset($child[$output_key])) { asort($child[$output_key]); $parent[$depth] = array_keys($child[$output_key]); $depth++; } else { for($j=$depth; $j>=1; $j--) { if(isset($parent[$j-1][0])) { break; } else { $depth--; } } } } else { if(!isset($root[0])) { break; } $output_key = array_shift($root); $output[$output_key] = $source[$output_key]; if(isset($child[$output_key])) { asort($child[$output_key]); $parent[0] = array_keys($child[$output_key]); $depth = 1; } } } return $output; } 這個function回傳的是排序完成的陣列 我有試著用比原po還複雜一些的陣列來測試,沒有什麼大問題 請原po測試看看囉~ -- ◢███◣ 秋符『秋の空と乙女の心』 ======= ●●ˍ▁ˍ_ 豊作『穀物神の約束』 豊かさと稔りの象徴 秋 穣子 Aki Minoriko 月 鍵 豊穣を司る程度の能力 BGM-稲田姫様に叱られるから ψ Celatic -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 175.181.164.84

01/03 16:26, , 1F
謝謝!來研究看看!
01/03 16:26, 1F
文章代碼(AID): #1F0ISGHe (PHP)
文章代碼(AID): #1F0ISGHe (PHP)