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

Advertisements

I have a php script that returns the images(or files) in a directory. The final output is a json of file names.

Below is the code of of what I have now and the result.

<?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);

The result is this json

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

The result I want is to append the url to each image add url as the key to each image.

[
 {"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"}
]

>Solution :

This will create an associative array with the right structure:

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

Leave a ReplyCancel reply