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

How to create a json string from a php array data

我正在寻找将具有值的数组转换为 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' => '');

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

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

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