1

I was trying to print some image details as a JSON array for that I just wrote a PHP code. Now it is printing only JSON objects like {"image0":"iphone.png","image1":"bbg.jpg"}, But I want it to be formatted as {"images":[{"image0":"iphone.png"},{"image1":"bbg.jpg"}]}. Please someone help me to fix this.

code

<?php
$return_array = array();
$files = glob('tmp/*');
$files = array_filter($files,create_function('$file','return (!is_dir($file));'));
usort($files,create_function('$a,$b','return filemtime($b) - filemtime($a);'));
foreach($files as $key => $file)
{
   $return_array["image".$key] = basename($file);
}
echo json_encode($return_array);    
?>
2
  • The data structure [{"image0":"iphone.png"},{"image1":"bbg.jpg"}] makes little sense. Why not have an array of strings? ["iphone.png", "bbg.jpg"]. Commented May 12, 2014 at 7:14
  • echo json_encode(array("images" => $return_array));??? Commented May 12, 2014 at 7:18

1 Answer 1

1

You could write your code like this after your foreach construct.

$new_arr = array();
foreach($return_array as $k=>$v)
{
 $new_arr['images'][]=array('image'.$k=>$v);
}
echo json_encode($new_arr);
Sign up to request clarification or add additional context in comments.

8 Comments

this wont print the '[]'
@ДмитрийИвановичМенделеев, Can you try now ?
now it will print 0 th index as [["tmp\/iphone.png"]
want to eliminate the first '['
@ДмитрийИвановичМенделеев: Use array('image'.$k=>$v) instead.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.