递归函数不返回数组

时间:2016-09-23 18:30:16

标签: php wordpress function recursion

我已经编写了下面的函数来按类别ID返回Worpress中所有类别的父ID。一切正常,除了它不返回阵列......任何建议都会很棒! : - )

$current_category = (int) $_GET['current_category'];
$cat_ids = array($current_category);

function getParentCatIds($current_category,$cat_ids){
    $child = get_category($current_category);
    $parent_id = $child->parent;
    if($parent_id !== 0){
        array_push($cat_ids, $parent_id);
        getParentCatIds($parent_id,$cat_ids);
    }else{
        var_dump($cat_ids); // <--- this returns the right array
        return $cat_ids; // <--- this returns NULL
    }
}

if($current_category){
    $cat_ids = getParentCatIds($current_category,$cat_ids);
    var_dump($cat_ids); // <--- this returns NULL
}

3 个答案:

答案 0 :(得分:1)

当你致电getParentCatIds()(第9行)时,你没有对函数的返回做任何事情。您应该分配或返回它。

答案 1 :(得分:0)

您应始终清理输入。一个很好的起点是filter_var()。使用validationsanitization的右侧标志并输入save(r)。请注意,FILTER_VALIDATE_*只会告诉您某些内容是否有效,而FILTER_SANITIZE_*实际上会清除您不想要的和潜在恶意数据中的数据。

$currentCat = intval( $_GET['current_category'] );
$currentCat = filter_var( $currentCat, FILTER_SANITIZE_NUMBER_INT );
if ( empty( $currentCat ) ) {
    // Abort – no valid data
    return;
}

然后,您可以构建一个包含原始类别父ID的数组。您可以使用回调作为第二个参数传递给array_walk()。回调本身已经分配了一个收集/最终数组,该数组作为参考传递并作为结果的目标。现在,您可以在一个不可靠的嵌套WordPress类别层次结构上递归循环。

// Base array
$parents = [];
$callback = function( $index, $id ) use ( &$parent ) {
    0 !== get_category( $id )->parent and $parents[] = $id;
};
array_walk( [ get_category( $currentCat )->parent ], $callback );

答案 2 :(得分:-4)

1)您应该在wordpress.stackexchange.com

询问

2)我认为解决方案是:在线9,而不是
getParentCatIds($parent_id,$cat_ids); 你应该有  return getParentCatIds($parent_id,$cat_ids);

相关问题