我有一个包含所有“类别”及其父母的数组,我想创建一个单独的数组,只包含指定类别的父类。
示例:
$categories = Array (
[1] => Array (
[ID] => 1
[CatName] => Recipes
[CatParent] => )
[2] => Array (
[ID] => 2
[CatName] => Desserts
[CatParent] => 1 )
[3] => Array (
[ID] => 3
[CatName] => Cakes
[CatParent] => 2 )
[4] => Array (
[ID] => 4
[CatName] => Main Course
[CatParent] => 1 )
)
那么,我如何遍历这个数组来找到所有“蛋糕”的父母(ID为2)?继续循环遍历所有父类别,直到该类别没有父类(NULL)。会返回如下数组的东西:
$categories = Array (
[1] => Array (
[ID] => 1
[CatName] => Recipes
[CatParent] => )
[2] => Array (
[ID] => 2
[CatName] => Desserts
[CatParent] => 1 )
[3] => Array (
[ID] => 3
[CatName] => Cakes
[CatParent] => 2 )
)
请注意,所有数组键都已与类别ID匹配,类别ID 3的父类别为2,类别2的父类别为1。
如果我想找到类别ID 4的父级,它将返回一个类别为4和类别1的数组。
答案 0 :(得分:1)
您的问题的解决方案将是使用这样的函数:
function get_parent_categories($category_array, $category){
$cat_id = null;
$parent_category_array = array();
foreach($category_array as $key => $cat){
if($cat['CatName'] == $category){
$cat_id = isset($cat['CatParent']) ? $cat['CatParent'] : null;
$parent_category_array[] = $category_array[$key];
break;
}
}
while($cat_id != null){
$parent_category_array[] = $category_array[$cat_id];
$cat_id = $category_array[$cat_id]['CatParent'];
}
return $parent_category_array;
}
现在按以下方式调用get_parent_categories()
函数,
// In this function call, $categories is your original category array
$parent_category_array = get_parent_categories($categories, 'Cakes');
// display $parent_category_array array
var_dump($parent_category_array);
这是live demo: