我在做foreach循环中的数组操作时做错了什么?

我有一个标题为$photos的数组,如下所示:

Array
(
    [0] => Array
        (
            [fileURL] => https://www.filepicker.io/api/file/UYUkZVHERGufB0enRbJo
            [filename] => IMG_0004.JPG
        )

    [1] => Array
        (
            [fileURL] => https://www.filepicker.io/api/file/WZeQAR4zRJaPyW6hDcza
            [filename] => IMG_0003.JPG
        )

)

现在我想创建一个名为$values的新数组,如下所示:

 Array
(
    [vshare] => Array
        (
            [IMG_0003.JPG] => Array
                (
                    [0] => https://www.filepicker.io/api/file/RqAN2jZ7ScC8eOx6ckUE
                )

            [IMG_0004.JPG] => Array
                (
                    [0] => https://www.filepicker.io/api/file/XdwtFsu6RLaoZurZXPug
                )

        )

)

为此,我尝试了以下代码:

$values = array();
        foreach($photos as $photo ) {
          $values['vshare'][$photo->filename] = array($photo->fileURL);
        }

然后,当我print_r($values)时,我得到了错误的输出:

Array
(
    [vshare] => Array
        (
            [] => Array
                (
                    [0] => 
                )

        )

)

有人可以纠正我在代码中犯的错误吗?

谢谢。


- >是对象的运算符,如在此问题中所讨论的那样。

尝试:

$values = array();
foreach($photos as $photo ) {
    $values['vshare'][$photo['filename']] = array($photo['fileURL']);
}

<?php

$values = array();
foreach($photos as $photo ) {
   $values['vshare'][$photo['filename']][0] = $photo['fileURL'];
}

你应该试试这个代码

$values = array();
foreach($photos as $photo) {
    $values['vshare'][$photo['filename']] = array(0 => $photo['fileURL']);
}

对我来说工作得很好。

链接地址: http://www.djcxy.com/p/58165.html

上一篇: What I'm doing wrong in following array manipulation in foreach loop?

下一篇: How to add index to foreach data from database?