-1

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"}
]
2
  • If the list at the end of your question is meant to represent an associative PHP array, then you've got a problem. In such an array all the keys have to be unique. Commented Nov 10, 2023 at 12:30
  • 1
    It was quite literally just a basic string append. It's hard for me to believe you couldn't crack that! Commented Nov 10, 2023 at 12:43

1 Answer 1

1

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 ];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.