You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何从子函数获取array_push操作后的$postsList最新值?

问题分析与解决方案

你遇到的问题核心是PHP数组的传递机制:默认情况下数组是按值传递的,也就是说你把$postsList传给child函数时,函数内部拿到的是原数组的一个副本,你在child里用array_push修改的只是这个副本,原数组(主函数里的$postsList)完全没变化。另外你的child函数没有返回值,所以主函数里array_push($postsList, $this->child(...))其实是往数组里塞了个null,这也不是你想要的结果。

下面给你两种可行的解决办法:

方法一:使用引用传递

把child函数的$postsList参数改成引用类型,这样函数内部操作的就是原数组本身,不需要返回值,主函数里也不用再push child的返回结果了。

修改后的代码:

public function index() { 
    ... 
    $postsList = []; 
    foreach ($categories->posts as $post) { 
        array_push($postsList, $post); 
    } 
    // 直接调用child,无需处理返回值
    $this->child($categories, $postsList); 
    dd($postsList); 
} 

// 参数前加&,表示传递原数组的引用
private function child($categories, &$postsList) { 
    if ($categories->childrenCategories->first()) { 
        foreach ($categories->childrenCategories as $childCategory) { 
            foreach ($childCategory->categories as $category) { 
                foreach ($category->posts as $post) { 
                    array_push($postsList,$post); 
                } 
            } 
            foreach ($childCategory->posts as $post) { 
                array_push($postsList,$post); 
            } 
            // 递归调用时同样操作原数组
            $this->child($childCategory,$postsList); 
        } 
    } 
}

方法二:让函数返回更新后的数组

如果不想用引用,也可以让child函数每次都返回更新后的数组,主函数和递归调用时都要接收这个返回值来更新原数组。

修改后的代码:

public function index() { 
    ... 
    $postsList = []; 
    foreach ($categories->posts as $post) { 
        array_push($postsList, $post); 
    } 
    // 接收child返回的更新后的数组
    $postsList = $this->child($categories, $postsList); 
    dd($postsList); 
} 

private function child($categories,$postsList) { 
    if ($categories->childrenCategories->first()) { 
        foreach ($categories->childrenCategories as $childCategory) { 
            foreach ($childCategory->categories as $category) { 
                foreach ($category->posts as $post) { 
                    array_push($postsList,$post); 
                } 
            } 
            foreach ($childCategory->posts as $post) { 
                array_push($postsList,$post); 
            } 
            // 递归调用时接收返回值,更新当前的$postsList
            $postsList = $this->child($childCategory,$postsList); 
        } 
    } 
    // 必须返回更新后的数组,否则上层拿不到修改结果
    return $postsList; 
}

两种方法都能解决你的问题,个人更推荐第一种引用传递的方式,代码更简洁,递归时也不用每次都赋值,效率也稍高一些(避免了数组的重复复制)。

内容的提问来源于stack exchange,提问作者DolDurma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:49:53