我希望将数组转换为json_encode格式,但是读取函数json_encode我找不到获得此结果的选项:
{
"image1":{"filename":"image1.jpg","alt":"","caption":""},
"image2":{"image2.jpg","alt":"","caption":""}
}
我的数组是:
$prod['images'] = 'image1.jpg,image2.jpg';
$images = explode(',', $prod['images']);
foreach($images as $img){
$get_path = pathinfo($img);
$path = $get_path['basename'];
$images_array[] = array(
$path => array('filename' => $img, 'alt' => '', 'caption' => '')
);
}
$final_images = json_encode($images_array);
我的问题是我怎么能像这样转换成json:
{
"image1":{"filename":"image1.jpg","alt":"","caption":""},
"image2":{"image2.jpg","alt":"","caption":""}
}
已解决:
$images_array[$path] = array('filename' => $img, 'alt' => '', 'caption' => '');
答案 0 :(得分:1)
您在循环中错误地构建了$images_array
。它应该是:
$images_array[$path] = array('filename' => $img, 'alt' => '', 'caption' => '');
注意:确保在循环之外声明$images_array = array();
。