如何从php数组数据创建一个json字符串

时间:2015-01-09 20:10:20

标签: php arrays json

我希望将数组转换为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' => '');

1 个答案:

答案 0 :(得分:1)

您在循环中错误地构建了$images_array。它应该是:

$images_array[$path] = array('filename' => $img, 'alt' => '', 'caption' => '');

注意:确保在循环之外声明$images_array = array();