Magento使用foreach循环选择查询不能正确循环

时间:2016-04-28 09:18:19

标签: php mysql magento

我写了以下代码:

try {
    $json = array('success' => true);
    $read = $this->read;
    $readresult = $read->fetchAll("SELECT * FROM brand");

    foreach($readresult as $r) {
        $json['brands'][] = array(
            'id'          => $r['brand_id'],
            'name'        => $r['name'],
            'description' => $r['description'],          
        );
    }

    return $json;
} catch (Exception $e) {
    $message = $e->getMessage();
    echo json_encode(array("status" => "500", "error" => $message));
}

在这段代码中,我试图显示数据库表中的所有品牌记录。

但问题是当我尝试输出结果时,它只显示一条记录。

任何人都可以检查一下是什么问题。

上面代码的输出是:

{
"success":true,
"products":[
    {
    "id":"4",
    "name":"Test",
    "href":"http:\/\/localhost:8‌​1\/magento\/index.php\/catalog\/product\/view\/id\/4\/",
    "thumb":"http:\/\/localho‌​st:81\/magento\/media\/catalog\/product\/cache\/0\/thumbnail\/9df78eab33525d08d6e‌​5fb8d27136e95\/images\/catalog\/product\/placeholder\/thumbnail.jpg",
    "pirce":"$11‌​1,111.00"
    }
]}

1 个答案:

答案 0 :(得分:0)

尝试这样,

     $json['brands'] = array();
     foreach($readresult as $r) {
            $brand = array(
                'id'          => $r['brand_id'],
                'name'        => $r['name'],
                'description' => $r['description'],          
            );
     array_push($json['brands'],$brand);
        }