while循环仅返回第一类及其产品

时间:2016-12-08 15:04:46

标签: php while-loop php-5.5

数据库返回所有值。但下面的while循环仅返回第一个类别及其产品。我想分别显示所有类别和产品。有人可以在此代码中找到问题吗?

elseif (isset($_GET['type']) && $_GET['type'] == 'getProducts') {
        $categoriesID = array();
        $categories = array();
        $category = array();
        $data = array();
        $current_category = '';

        while ($results = $query->fetch_assoc()) {

            if (!in_array($results['category_id'], $categoriesID)) {
                $categoriesID[] = $results['category_id'];

                $item = array();
                while ($resultdata = $query->fetch_assoc()) {

                    //IMAGE PATH
                    $store_id = $store_data['store_id'];
                    define('DIR_IMAGE', '../../image/uploads/' . $store_id . '/cache/');

    // RESIZE IMAGE
                    $extension_pos = strrpos($resultdata['product_image_url'], '.'); // find position of the last dot, so where the extension starts
                    $thumb = substr($resultdata['product_image_url'], 0, $extension_pos) . '-500x500' . substr($resultdata['product_image_url'], $extension_pos);
    // RESIZE IMAGE
    //IMAGE PATH
                    if ($resultdata['category_id'] == $results['category_id']) {

                        $items = array('id' => $resultdata['product_id'], 'name' => $resultdata['product_name'],
                            'price' => $resultdata['product_price'],
                            'link' => DIR_IMAGE . $thumb);
                        array_push($item, $items);
                    }
                }

                $categories[] = array('id' => $results['product_id'], 'cat_id' => $results['category_id'], 'category_name' => $results['category_name'],
                    'category_description' => '',
                    'data' => $item);
            }
        }
        echo json_encode($categories);

        //var_dump($categories);die;
    }

2 个答案:

答案 0 :(得分:0)

在while循环中使用fetchall,如下所示

 while ($results = $query->fetchAll()) {

答案 1 :(得分:0)

当我简化代码时,我得到:

while ($results = $query->fetch_assoc()) {
     ...
     while ($resultdata = $query->fetch_assoc()) {
        ....
     }
}

很明显外部while循环只会运行一次,因为对fetch_assoc()的所有后续$query调用都将在内循环中执行。