我有一个下面的数组它显示父母和孩子的顺序,但我需要按父母订购
$input = array(
array(
'ID' => 1,
'parent_id ' => null
),
array(
'ID' => 2,
'parent_id ' => 1
),
array(
'ID' => 3,
'parent_id ' => 5
),
array(
'ID' => 4,
'parent_id ' => 3
),
array(
'ID' => 5,
'parent_id ' => 2
)
);
我使用相同的方式与父级排序,但具有相同的错误
function cmp($a, $b) {
if ($a['parent_id'] == $b['parent_id']) {
return 0;
}
return ($a['parent_id'] < $b['parent_id']) ? -1 : 1;
}
uasort($data, 'cmp');
echo '<pre>';
print_r($data);
echo '</pre>';
我需要像这样回来
array(
array(
'id' => 1,
'parent_id' => null
),
array(
'id' => 2,
'parent_id' => 1
),
array(
'id' => 5,
'parent_id' => 2
),
array(
'id' => 3,
'parent_id' => 5
),
array(
'id' => 4,
'parent_id' => 3
)
);
如果你能比php更好地帮助我使用mysql
CREATE TABLE cars
(`id` int, `parent_id` int)
;
INSERT INTO cars
(`id`, `parent_id`)
VALUES
(1, 0),
(2, 1),
(3, 5),
(4, 3),
(5, 2)
;
SELECT
id
FROM
cars
ORDER BY
CASE WHEN parent_id = 0 THEN id ELSE parent_id END,
parent_id,
id
答案 0 :(得分:0)
SOF上有很多解决方案,所以我尝试了一些(提示),我想出了这个......
usort($input, function($a,$b){ return $a['ID']-$b['PARENT'];} );
var_dump($input);
这可以为您提供所追求的目标。
<强>更新强> 好的,这让我烦恼......所以我想出了这个。试一试!
SELECT c1.id, c1.parent_id FROM cars c1
LEFT JOIN cars c2 ON c2.id = c1.parent_id
GROUP BY c2.parent_id
你必须玩这个并测试它。
答案 1 :(得分:0)
首先,您似乎在
parent_id
密钥中的 _id 后面有一个空格。无论如何,usort()
是执行您想要的排序的最短方式:
GIVEN ARRAY:
<?php
$input = array(
array(
'ID' => 1,
'parent_id' => null
),
array(
'ID' => 2,
'parent_id' => 1
),
array(
'ID' => 3,
'parent_id' => 5
),
array(
'ID' => 4,
'parent_id' => 3
),
array(
'ID' => 5,
'parent_id' => 2
)
);
<强> ALGORITM:强>
<?php
usort($input,
function($prev, $next){
return $prev['parent_id']> $next['parent_id'];
}
);
var_dump($input);
上游的结果:
array (size=5)
0 =>
array (size=2)
'ID' => int 1
'parent_id' => null
1 =>
array (size=2)
'ID' => int 2
'parent_id' => int 1
2 =>
array (size=2)
'ID' => int 5
'parent_id' => int 2
3 =>
array (size=2)
'ID' => int 4
'parent_id' => int 3
4 =>
array (size=2)
'ID' => int 3
'parent_id' => int 5
如果您喜欢非常长,怪异,奇怪,错综复杂且乏味的解决方法,这个功能可能会有所帮助。 Quick Test.
<?php
function orderByPID($arrInput, $direction='asc'){
$arrSorted = [];
$arrPID = [];
foreach($arrInput as $iKey=>$subArray){
$pid = ($subArray['parent_id']==null) ? 0 : $subArray['parent_id'];
$arrPID[] = $pid;
}
$flipped = array_flip($arrPID);
if($direction == 'asc'){
ksort($flipped);
}else{
krsort($flipped);
}
foreach($flipped as $pid=>$index){
$pid = ($pid == '') ? null : $pid;
foreach($arrInput as $iKey=>$subArray){
if($subArray['parent_id'] == $pid){
$arrSorted[] = $subArray;
break;
}
}
}
return $arrSorted;
}
var_dump( orderByPID($input) );
VAR_DUMP的结果:
array (size=5)
0 =>
array (size=2)
'ID' => int 1
'parent_id' => null
1 =>
array (size=2)
'ID' => int 2
'parent_id' => int 1
2 =>
array (size=2)
'ID' => int 5
'parent_id' => int 2
3 =>
array (size=2)
'ID' => int 4
'parent_id' => int 3
4 =>
array (size=2)
'ID' => int 3
'parent_id' => int 5