Php 递归函数不返回数组

Php 递归函数不返回数组,php,wordpress,function,recursion,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_categ

我已经编写了下面的函数,通过类别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
}
1.你应该早问一声 2我认为解决办法是:在第9行,而不是 GetParentCATID$parent\u id,$cat\u id; 你应该 返回getParentCatIds$parent\u id$cat\u id

当调用getParentCatIds第9行时,您没有对函数的返回执行任何操作。您应该分配或返回它。

您应该始终清理输入。一个好的起点是。为和使用正确的标志会使您的输入节省。请记住,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 );

我不敢相信你得了13.5 K分,并且给出了这样的回答:/棒极了!这是一个普通的php问题,而不是Wordpress问题。这就是为什么我把它贴在这里…:-@海德堡。你不必相信:Deisgn Bytes——你犯了一个你在这里问到的小错误,我只是建议把它贴在适当的地方。还有一些关于PHP的问题,以及与WP相关的函数的更高级的知识。我已经更新了答案。有接近投票的标志。你最不应该做的事情就是用1个答案让人们在这2个标题上脱颖而出这是公众羞辱和3个大写字母锁,你很乐意忽略。我错了!你说得太对了!回归就是解决办法!:-它仅在parent_id=0时返回,请参见第7行。所以这没问题。最高级别为0。回程在12号线,我错了!你说得太对了!回归就是解决办法!:-塔克斯!对于反馈。。。你是说int$\u GET['current\u category']不安全吗$_GET['current_category']是一个数字,当我将它转换为int时,它是零还是正确的数字?还是我遗漏了什么?卫生设施是不必要的?@DesignBytes有很多东西可以是数字,例如IP地址。您应该始终验证和清理输入。