dongyi0210 2012-04-05 18:32
浏览 18

大阵列,问题呼应它

I got this problem trying to echo out a big array.

print_r looks like this: http://codepaste.net/5js97a

There's no problem echoing out the first 2 rows like this in a foreach loop: $item['name'], but for the rest of them deeper inside the array, I just get an error.

Thanks!

Code:

function categories($parent = NULL) {
      $query = $this->db->where('parent_id', $parent)->get('categories');
      $results = $query->result_array();

      foreach($results as $result) {
           $child_array = Forummodel::categories($result['id']);
           if(sizeof($child_array) == 0) {
                array_push($results, $result['name']);
           } else {
                array_push($results, array($result['name'], $child_array));
           }
      }

      return $results;
} 

Im also using codeigniter

  • 写回答

1条回答 默认 最新

  • doulvli9462 2012-04-05 19:33
    关注

    You are iterating on an increasing array. Here is your code:

    function categories($parent = NULL) {
        $query = $this ->db ->where('parent_id', $parent) ->get('categories');
        $results = $query->result_array();
        foreach($results as $result) {
            $child_array = Forummodel::categories($result['id']);
            if(sizeof($child_array) == 0) {
                array_push($results, $result['name']);
            } else {
                array_push($results, array($result['name'], $child_array));
            }
        }
        return $results;
    }
    

    The foreach is iterating down the array $results and you are adding to it with each loop, plus, by the time you hit an iteration where $result doesn't contain 'id' or 'name' you are probably getting the error. You might want to put the child arrays into another array and merge them after the foreach loop if you still want to do that.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号