2012-06-20 121 views
0

我想弄清楚,如果我能做到一個數組while循環內的數組?

while($row = $retail -> fetch(PDO::FETCH_ASSOC)){ 

$json['data'][] = array(

'id'=>$row['idretailers'], 
"category"=>$row['category'], 
"headline"=>$row['headline'], 
'price'=> array ("full_price" => $row['price']), 
'description'=>$row['description'], 
"comments" => array(
while($row_c = $comments -> fetch(PDO::FETCH_ASSOC)){ 

// more items 
}) 
); 
} 

有意見中的while循環while循環,這可能嗎?

謝謝!

+5

你試過了嗎? –

+0

只需嘗試一下,看看你會得到一個語法錯誤,並嘗試一種不同的方法。短:不,這是不可能的。 – Yoshi

+1

它的可能,除非你嘗試 – Khurram

回答

1

既然你將它插入一個JSON字符串,像這樣做:

while($row = $retail -> fetch(PDO::FETCH_ASSOC)){ 

    $json['data'][] = array(

     "id"=>$row['idretailers'], 
     "category"=>$row['category'], 
     "headline"=>$row['headline'], 
     "price"=> array ("full_price" => $row['price']), 
     "description"=>$row['description'], 
     "comments" => $comments->fetchAll() 
    ); 
} 

否則,你可以撥打implode的評論:

while($row = $retail -> fetch(PDO::FETCH_ASSOC)){ 

    $json['data'][] = array(

     "id"=>$row['idretailers'], 
     "category"=>$row['category'], 
     "headline"=>$row['headline'], 
     "price"=> array ("full_price" => $row['price']), 
     "description"=>$row['description'], 
     "comments" => implode("\n", $comments->fetchAll()); 
    ); 
} 
+1

+1和答案的完整腳本的例子,和其他方法的方法 – hellomello

2

你寫它是不可能的,但有一個簡單的解決方式:

"comments" => $comments -> fetchAll(PDO::FETCH_ASSOC) 
+0

+1爲簡單例子。謝謝! – hellomello