[英]PHP - Loops and multidimensional arrays
我在這里閱讀了很多其他文章,但確實可以解決我的問題。 我正在從MySQL數據庫訪問數據:圖像ID和圖像名稱。 我可以通過以下方式輕松獲取信息:
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),
但這不起作用。 有人有主意嗎?
您在混淆字符串和數組。 只需創建一個空數組,然后在循環中向其添加元素:
$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;
嘗試這個:
<?php
$newItem = array();
while($row = mysqli_fetch_array( $result ))
{
$newItem['images'][] = array(
'link' => $imguri.$row['name'],
'description' => 'My image'
);
}
var_dump($newItem);
在while循環中使用php array_push()方法。
$ images ['images'] = array();
while($ row = mysqli_fetch_array($ result)){
$ image = array('link'=> $ imguri。$ row ['name'],'description'=>'我的圖像',);
array_push($ images ['images'],$ image);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.