问题
I have an array with all categories stored in it:
$allCatArray = array(
['departments/outdoor/123123/'] => stdClass Object
(
[i] => 1
[id] => 'departments/outdoor/123123/'
[pid] => 'departments/outdoor/'
[name] => 'Child Category Name'
)
['departments/outdoor/'] => stdClass Object
(
[i] => 1
[id] => 'departments/outdoor/'
[pid] => '0'
[name] => 'Main Category Name'
)
I need detect the highest category in hierarchy when i have id of lower category in hierarchy. So I have this function:
function findMainCategoryFromAllCatArray($initial_category, $allCatArray) {
$pid = trim($allCatArray[$initial_category]->pid);
if($pid != "0") {
findMainCategoryFromAllCatArray($pid, $allCatArray);
}
elseif($pid == "0") {
var_dump($allCatArray[$initial_category]->name); // this var dump returns normal value
return $allCatArray[$initial_category]->name;
}
else {
return false;
}
}
I'm getting trouble when trying to use this function:
$category_name = findMainCategoryFromAllCatArray('departments/outdoor/123123/', $allCatArray);
var_dump($category_name); // returns NULL instead of "Main Category Name"
Any ideas?
回答1:
replace this:
if($pid != "0") {
findMainCategoryFromAllCatArray($pid, $allCatArray);
}
with
if($pid != "0") {
return findMainCategoryFromAllCatArray($pid, $allCatArray);
}
because when $pid != "0"
on the start, the function return nothing -> your NULL
value
来源:https://stackoverflow.com/questions/40428865/php-function-returns-null-instead-of-string