繁体   English   中英

PHP-循环和多维数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM