我在如何使用javascript列出数组子项时遇到了麻烦。 这是我在php中的代码:
$arr = array();
foreach ($categories as $key => $cat) {
if($cat['parent_id'] == 0){
$arr[$cat['id']] = $cat;
}else{
$arr[$cat['parent_id']][] = $cat;
}
}
输出是:
Array (
[1] => Array (
[id] => 1
[parent_id] => 0
[name] => A
[0] => Array (
[id] => 2
[parent_id] => 1
[name] => B
)
[1] => Array (
[id] => 3
[parent_id] => 1
[name] => C
)
[2] => Array (
[id] => 4
[parent_id] => 1
[name] => D
)
)
[5] => Array (
[id] => 5
[parent_id] => 0
[name] => E
[0] => Array (
[id] => 6
[parent_id] => 5
[name] => F
)
[1] => Array (
[id] => 7
[parent_id] => 5
[name] => G
)
)
答案 0 :(得分:0)
尝试:
print_r($cat[1][name]);
结果是什么?
答案 1 :(得分:0)
$paren_arr = array("id"=>0, "children"=>array()); // Top parent category:
foreach ($arr as $key=>$child ) {
/*If parent of current array is TOP (parent_id==0)
Add to TOP parent array. (TOP['children'][] = current array)
Else
Walk through each children of TOP parent. (parent_id!=0)
If child of TOP parent's ID is Parent id of current array
Add to TOP parent->child, this array. (TOP['children']['CHILD_ID'][] = current)
*/
if ( !is_array($param) )
continue;
if ( $param['parent_id']==0 ) {
$paren_arr['children'][$param['name']] = $param;
} else {
foreach ( $paren_arr['children'] as $name=>$child_param ) {
if ( $param['parent_id']==$child_param['id'] ) {
$paren_arr['children'][$name]['children'][$param['name']] = $param;
}
}
}
}
可以优化此函数(使用递归)以使用不同的嵌套级别。