gpt4 book ai didi

php - 在 foreach 循环中循环的数组中添加项目

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:14 25 4
gpt4 key购买 nike

所以我有一个 foreach 循环,它循环遍历一组项目。 checkIfSubCategorie() 返回一个包含新项目的数组。

我想将所有这些项目放在 $subcategorien 数组中。这很好用。问题是这些项目没有经过初始的 foreach 循环。这可能吗?如果可能,怎么办?

foreach($subcategorien as $subcat) {

//make array with all subcategorien
$newarray = self::checkIfSubCategorie($subcat);

if(is_array($newarray)) {
foreach($newarray as $a) {

// add item to subcategorien
array_push($subcategorien, $a);
}
}
}

这是$subcategorien 数组之前初始foreach 循环:

array(2) {
[0]=> string(3) "701"
[1]=> string(3) "702"
}

$newarray 的 var_dump:

array(1) {
[0]=> string(1) "8"
}
bool(false)

这是 $subcategorien 数组 foreach 循环之后:

array(3) {
[0]=> string(3) "701"
[1]=> string(3) "702"
[2]=> string(1) "8"
}

结果应该是:

array(3) {
[0]=> string(3) "701"
[1]=> string(3) "702"
[2]=> string(1) "8"
[3]=> string(1) "9"
}

最佳答案

您正在寻找的是递归函数。像这样的东西:

function getCategoryChildren($categoryParentId, $categories = array()) {
// TODO: query to get all the categories by their parents id
while ($row = $stmt->fetch_assoc()) {
$categories[] = $row['category_id'];
$categories = getCategoryChildren($row['category_id'], $categories);
}
return $categories;
}

$allCategories = getCategoryChildren(0);

关于php - 在 foreach 循环中循环的数组中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34308291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com