What I'm doing wrong in following array manipulation in foreach loop?

I've an array titled $photos as follows:

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
        )

)

Now I want to create a new array titled $values as follows :

 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
                )

        )

)

For this I tried following code :

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

Then I got following wrong output when I print_r($values) :

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

        )

)

Can someone please correct the mistake I'm making in my code?

Thanks.


-> is operator for objects, as expleined in this question.

Try:

$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'];
}

you should try this code

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

Works fine for me.

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

上一篇: 这个运算符是什么“=>”?

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