当我想在我的数据中创建树结构时,我遇到了问题,这是我的样本数据
$categories = array(
array(
'id' => 2 ,
'name' => 'banana',
'parent' => 1
),
array(
'id' => 1 ,
'name' => 'fruit',
'parent' => 0
),
array(
'id' => 3 ,
'name' => 'Monkey',
'parent' => 4
),
array(
'id' => 4 ,
'name' => 'Animal',
'parent' => 0
),
array(
'id' => 5 ,
'name' => 'apple',
'parent' => 1
),
array(
'id' => 6 ,
'name' => 'Cat',
'parent' => 4
),
array(
'id' => 7 ,
'name' => 'Animal Water',
'parent' => 1
),
array(
'id' => 8 ,
'name' => 'fish',
'parent' => 7
),
array(
'id' => 9 ,
'name' => 'frog',
'parent' => 7
)
);
然后我想重组那个数组
$fix = array(
array(
'id' => 4 ,
'name' => 'Animal',
'parent' => 0,
'child' => array(
array(
'id' => 7 ,
'name' => 'Animal Water',
'parent' => 1,
'child' => array(
array(
'id' => 8 ,
'name' => 'fish',
'parent' => 7
),
array(
'id' => 9 ,
'name' => 'frog',
'parent' => 7
)
)
),
array(
'id' => 3 ,
'name' => 'Monkey',
'parent' => 4
),
array(
'id' => 6 ,
'name' => 'Cat',
'parent' => 4
),
)
),
array(
'id' => 1 ,
'name' => 'fruit',
'parent' => 0,
'child' => array(
array(
'id' => 2 ,
'name' => 'banana',
'parent' => 1
),
array(
'id' => 5 ,
'name' => 'apple',
'parent' => 1
)
)
)
);
所以我尝试使用这个功能,但没有帮助我。
$GLOBALS['viyancs'] = array();
$GLOBALS['i'] = 0;
function finding_parent($categories) {
foreach ($categories as $value) {
//finding parent
if ($value['parent'] === 0 ) {
$GLOBALS['viyancs'][$GLOBALS['i']][$value['id']]= $value;
$GLOBALS['i']++;
continue;
}
if (isset($GLOBALS['viyancs'][$GLOBALS['i']][$value['parent']])) {
$GLOBALS['viyancs'][$GLOBALS['i']][$value['parent']]['child']= $value;
}
$GLOBALS['i']++;
}
return $GLOBALS['viyancs'];
}
var_dump(finding_parent($categories));
还有其他任何建议吗?
答案 0 :(得分:0)
你有一个category_id和parent_id
的类别数组阵 ( [0] =>排列 ( [id] => 1 [parent] => 0 [name] =>人 )
[1] => Array
(
[id] => 2
[parent] => 0
[name] => Woman
)
[2] => Array
(
[id] => 3
[parent] => 1
[name] => Tshirt
)
[3] => Array
(
[id] => 4
[parent] => 1
[name] => Jeans
)
[4] => Array
(
[id] => 5
[parent] => 2
[name] => woman jeans
)
[5] => Array
(
[id] => 6
[parent] => 2
[name] => woman top
)
[6] => Array
(
[id] => 7
[parent] => 3
[name] => branded tshirt
)
[7] => Array
(
[id] => 8
[parent] => 4
[name] => branded jeans
)
)
答案 1 :(得分:0)
function getCategory($category_array)
{
foreach($category_array as $key => $category_data):
$cat_option_array;
if($category_data['parent']==0)
{
$cat_option_array .= "<option value=".$category_data['id'].">".$category_data['name']."</option>";
foreach($category_array as $subcategory_key => $subcategory_data):
if($category_data['id']==$subcategory_data['parent'])
{
$cat_option_array .= "<option value=".$subcategory_data['id'].">--".$subcategory_data['name']."</option>";
foreach($category_array as $level2categorykey => $level2category):
if($level2category['parent']==$subcategory_data['id'])
{
$cat_option_array .= "<option value=".$level2category['id'].">----".$level2category['name']."</option>";
}
endforeach;
}
endforeach;
}
endforeach;
echo $cat_option_array;
}