表格
cat_id | cat_parent_id | cat_name
---------------------------------
12 | 0 | Car
13 | 0 | Manga
14 | 12 | Volvo
15 | 12 | Mercedes-Benz
16 | 13 | Naruto
17 | 13 | Hunter X Hunter
18 | 0 | Animals
我试图获取数据库中的类别并将其放入数组然后使用该数组后,为下拉列表构建代码。这是代码BELOW。
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;
if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('id' => $id, 'name' => $name, 'children' => array());
} else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
}
}
$list = '';
foreach ($categories as $key => $value) {
$name = "--" . strtoupper($value['name']) . "--";
$children = $value['children'];
$list .="<option value=\"{$value['id']}\"";
if ($value['id'] == $catId) {
$list.= " selected";
}
$list .= ">$name</option>\r\n";
foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}
$list .= ">{$child['name']}</option>\r\n";
}
}
$ categories array的最终值
Array
(
[12] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 14
[name] => Volvo
)
[1] => Array
(
[id] => 15
[name] => Mercedez-Benz
)
)
)
[13] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 16
[name] => Naruto
)
[1] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
)
)
[18] => Array
(
[id] => 18
[name] => Animals
[children] => Array
(
)
)
)
但我想按键'name'的值对$ categories进行排序。
我尝试了很多次,到目前为止,这是我的解决方案。
function sortByName($a, $b) {
return strcmp($a["name"], $b["name"]);
}
usort($categories,"sortByName");
foreach($categories as $k => $v){
foreach($v as $kk => $vv) {
if ($kk == "children") {
usort($vv,"sortByName");
print_r($vv );
}
}
}
我的问题是,即使第一级关键'名称'排序很好,但我对第二级排序的解决方案不起作用。
并且当排序发生时,我排序的数组的索引变为0 1 2 3.
例如,当我按键'name'的值排序时,18 12 13将变为0 1 2
Array(
[18] => Array
(
[id] => 18
[name] => aa
)
[12] => Array
(
[id] => 12
[name] => Car
)
[13] => Array
(
[id] => 13
[name] => Manga
)
)
我怎么能排序,但我也想要18 12 13不改变?
所以我希望我的$ categories数组成为这个
Array
(
[18] => Array
(
[id] => 18
[name] => Animals
[children] => Array
(
)
)
[12] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 15
[name] => Mercedes-Benz
)
[1] => Array
(
[id] => 14
[name] => Volvo
)
)
)
[13] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
[1] => Array
(
[id] => 16
[name] => Naruto
)
)
)
)
答案 0 :(得分:2)
付出太多努力。使用NAME作为数组KEY,然后使用ksort
按键排序答案 1 :(得分:0)
我认为问题在于PHP不会将这些数字索引解释为键,只是索引,因此在排序后它不会保留它们。如果你将它们转换为字符串,然后进行排序,我怀疑它会保留它们。或者,你可以用你的名字交换数字键(当然,如果名称是唯一的),做一个简单的ksort(如前面的答案所示),然后再交换它们。
答案 2 :(得分:0)
你使用uksort来执行你想要的。但是你的设计有问题。
像@Lukasz Kujawa所说,php数组被设计为在O(1)中访问。您的设计作为C数组,强制所有内容为O(n)并在此过程中添加一个步骤。
我会用uksort给你“解决方案”,但对我来说这不是一件好事。
uksort($categories,function($a,$b)use($categories){
return return strcmp($categories[$a]["name"], $categories[$b]["name"]);
}