如何从 JSON 数据中获取数组并将其转换为所需的新数组格式?

How to get array from JSON data and convert it into desired new array format?

我正在关注 JSON 请求数据:

data = "{\"photo\":[{\"fileURL\":\"https:\/\/www.filepicker.io\/api\/file\/RqAN2jZ7ScC8eOx6ckUE\",\"filename\":\"IMG_0003.JPG\"},{\"fileURL\":\"https:\/\/www.filepicker.io\/api\/file\/XdwtFsu6RLaoZurZXPug\",\"filename\":\"IMG_0004.JPG\"}]}";

我想将上述 JSON 数据制作成以下格式的数组:

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
                )

        )

)

实际的 JSON 请求数据可能非常庞大。供您参考,我只在其中使用了两个这样的元素。

那么有人可以帮我提供一种有效地获得所需新阵列的方法吗?

提前致谢。

$data = json_decode($data,true);

好的,然后试试这个:

$data = "{\"photo\":[{\"fileURL\":\"https:\/\/www.filepicker.io\/api\/file\/RqAN2jZ7ScC8eOx6ckUE\",\"filename\":\"IMG_0003.JPG\"},{\"fileURL\":\"https:\/\/www.filepicker.io\/api\/file\/XdwtFsu6RLaoZurZXPug\",\"filename\":\"IMG_0004.JPG\"}]}";
$data = json_decode($data,true);
$NewData = false;
foreach($data['photo'] as $k=>$d){
    $NewData['vshare'][$d['filename']][] = $d['fileURL'];
}
var_dump($NewData);

我想这会做你想要的。

<?php
$data = "{\"photo\":[{\"fileURL\":\"https:\/\/www.filepicker.io\/api\/file\/RqAN2jZ7ScC8eOx6ckUE\",\"filename\":\"IMG_0003.JPG\"},{\"fileURL\":\"https:\/\/www.filepicker.io\/api\/file\/XdwtFsu6RLaoZurZXPug\",\"filename\":\"IMG_0004.JPG\"}]}";

$obj = json_decode($data);

$new_ar = array();
foreach ( $obj->photo as $photo ) {
    $new_ar['vshare'][$photo->filename] = array($photo->fileURL);
}
print_r($new_ar);

应该生成

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
                )

        )

)