php函数返回null而不是string

时间:2016-11-04 17:45:49

标签: php function recursion tree

我有一个包含所有类别的数组:

$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'
                          )

当我在层次结构中具有较低类别的id时,我需要检测层次结构中的最高类别。所以我有这个功能:

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;
  }
}

我在尝试使用此功能时遇到了麻烦:

$category_name = findMainCategoryFromAllCatArray('departments/outdoor/123123/', $allCatArray);
var_dump($category_name); // returns NULL instead of "Main Category Name"

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

替换这个:

if($pid != "0") {
    findMainCategoryFromAllCatArray($pid, $allCatArray);
}

if($pid != "0") {
   return findMainCategoryFromAllCatArray($pid, $allCatArray);
}

因为在$pid != "0"开始时,该函数不返回任何内容 - >您的NULL