在 php 中将数组更改为关联数组以相应地获取键值对 [duplicate]

Change an array to an associative array in php to get key value pairs accordingly [duplicate]

提问人:winfred adrah 提问时间:11/10/2023 更新时间:11/11/2023 访问量:42

问:

我有一个php脚本,可以返回目录中的图像(或文件)。最终输出是文件名的 json。

以下是我现在拥有的代码和结果。

<?php

$files = array();

$dir = opendir('/folderpath');
while ($file = readdir($dir)) {
    if ($file == '.' || $file == '..') {
        continue;
    }

    $files[] = $file;
}

header('Content-type: application/json');
echo json_encode($files);

结果是这个 json

["1.png","2.jpg","4.jpg","3.png"]

我想要的结果是将 url 附加到每个图像,将 url 添加为每个图像的键。

[
 {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-1.png"},
 {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-2.jpg"},
 {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-3.jpg"},
 {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-4.jpg"},
 {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-5.jpg"},
 {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-6.jpg"}
]
php json 关联数组

评论

0赞 KIKO Software 11/10/2023
如果问题末尾的列表旨在表示一个关联的 PHP 数组,那么您就有问题了。在这样的数组中,所有键都必须是唯一的。
1赞 nice_dev 11/10/2023
从字面上看,它只是一个基本的字符串附加。我很难相信你无法破解它!

答:

1赞 ADyson 11/10/2023 #1

这将创建一个具有正确结构的关联数组:

$files[] = [ "url" => "https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-".$file ];