提问人:winfred adrah 提问时间:11/10/2023 更新时间:11/11/2023 访问量:42
在 php 中将数组更改为关联数组以相应地获取键值对 [duplicate]
Change an array to an associative array in php to get key value pairs accordingly [duplicate]
问:
我有一个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"}
]
答:
1赞
ADyson
11/10/2023
#1
这将创建一个具有正确结构的关联数组:
$files[] = [ "url" => "https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-".$file ];
评论