Re: [請益] 請問如何排序?很困難…
個人不太喜歡用遞迴,所以只用迴圈實現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
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):
1
14
PHP 近期熱門文章
PTT數位生活區 即時熱門文章