如何在php中打印格式化的JSON数组


How to print formatted JSON array in php

我试图打印一些图像细节作为JSON数组,我刚刚写了一个PHP代码。现在它只打印JSON对象,如{"image0":"iphone.png","image1":"bbg.jpg"},但我希望它被格式化为{"images":[{"image0":"iphone.png"},{"image1":"bbg.jpg"}]}。请有人帮我解决这个问题。

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

您可以在foreach构造之后编写这样的代码。

$new_arr = array();
foreach($return_array as $k=>$v)
{
 $new_arr['images'][]=array('image'.$k=>$v);
}
echo json_encode($new_arr);