dpvomqeu396484 2015-12-16 09:30
浏览 85
已采纳

在foreach循环中循环的数组中添加item

So I have a foreach loop which loops though an array of items. The checkIfSubCategorie() returns an array with new items.

I want to place all these items in the $subcategorien array. This works good. The problem is that those items don't go through the initial foreach loop. Is this possible and if yes, how?

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

This is the $subcategorien array before the initial foreach loop:

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

var_dump of $newarray:

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

This is the $subcategorien array after the foreach loop:

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

The result should be:

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

3条回答 默认 最新

  • douwang4374 2015-12-16 09:58
    关注

    What you are looking for is called recursive function. Something like:

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?