2015-04-14 183 views
0

我一直在閱讀很多其他帖子,但確實解決了我的問題。我正在訪問來自MySQL DB的數據:圖像ID和圖像名稱。我可以很容易地獲得與信息:PHP - 循環和多維數組

while($row = mysqli_fetch_array($result)) { 

echo $row['name']; 

} 

我在這裏取一個形象的名字,我需要寫一個循環來插入圖像,另一個數組是這樣的:

$newItem = array(

//stuff like name, id, tax id etc. 
//... 
//, 

'images' => array(
    array(
     'link' => 'http://www.example.com/images/image1.jpg', 
     'description' => 'My image', 

     ), 

    array(
     'link' => 'http://www.example.com/images/image2.jpg', 
     'description' => 'My Image 2', 
     ), 

//maybe more images here ... 

    ), 

我第一次嘗試解決這是把提取的數據到一個變量:

while($row = mysqli_fetch_array($result)) { 
    // DB access - > $row['name'] 

    $images .= 
    array(
     'link'  => $imguri.$row['name'], //$imguri is the server link 
     'description' => 'My image', //not important 


     ).','; //with or without comma -> no success 
    } 

然後插入變量:

'images' => array($images), 

但這並不奏效。有人有想法嗎?

回答

0

試試這個:

<?php 
$newItem = array(); 

while($row = mysqli_fetch_array($result)) 
{ 
    $newItem['images'][] = array(
     'link'  => $imguri.$row['name'], 
     'description' => 'My image' 
    ); 
} 

var_dump($newItem); 
+0

這適用於我......謝謝 – Shockproof

0

你在混淆字符串和數組。只需創建一個空數組,並在循環元素添加到它:

$images = array(); 
while($row = mysqli_fetch_array($result)) { 

    $images[] = 
    array(
     'link'  => $imguri.$row['name'], //$imguri is the server link 
     'description' => 'My image', //not important  
     ); 
} 

// 
'images' => $images; 
+0

我明白了一點,但unforunately它不工作 – Shockproof

+0

@Shockproof請詳細說明「不工作」 - 也許你目前的,不工作的代碼更新您的問題,包括你正在 – Steve

+0

對不起錯誤信息因爲不夠清楚:當我「print_r」或「var_dump」數組時,它們總是空的。 – Shockproof

0

使用PHP array_push(在while循環)方法。
$ images ['images'] = array();
而($行= mysqli_fetch_array($結果)){
$圖像= 陣列( '鏈路'=> $ imguri。$行[ '名稱'], '描述'=> '我的圖像', );
array_push($ images ['images'],$ image);
}

+0

var_dump顯示我:array(1){[「images」] => array(0){}} - 如此不幸它不起作用 – Shockproof

+0

這對我有用。 – ajit

+0

你的意思是var_dump($ images ['images']);? – Shockproof