首页 > 解决方案 > 如何修改此 PHP 代码以将数据发送到服务器上的 json 文件,如下所示 json 格式

问题描述

 <?php  
 $message = '';  
 $error = '';  
 if(isset($_POST["submit"]))  
 {  
      if(empty($_POST["title"]))  
      {  
           $error = "<label class='text-danger'>Enter  details</label>";  
      }  
      else if(empty($_POST["image"]))  
      {  
           $error = "<label class='text-danger'>Enter Written By</label>";  
      }  
      else  
      {  
           if(file_exists('myfile.json'))  
           {  
                $current_data = file_get_contents('myfile.json');  
                $array_data = json_decode($current_data, true);  
                $extra = array(  
                     'title'  =>     $_POST['title'],  
                     'image'  =>     $_POST["image"],  
                     'link'   =>     $_POST['link'],  
                     'info'   =>     $_POST['info'],  
                );  
                $array_data[] = $extra;  
                $final_data = json_encode($array_data);  
                if(file_put_contents('myfile.json', $final_data))  
                {  
                     $message = "<label class='text-success'>Added Successfully</p>";  
                }  
           }  
           else  
           {  
                $error = 'JSON File not exits';  
           }  
      }  
 }  
 ?>

以上是我用于将数据发送到服务器上存在的 json 的 PHP 代码。

{
"Apple": [
  {
    "title": "iphone5",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  },
  
  {
    "title": "iphone6",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  }
]
}

以上是我在使用 PHP 提交数据后想要拥有的 json 文件格式,它不应该覆盖 myfile 或类似的东西,我希望它使用 PHP 在数组中添加更多的孩子

[
  {
    "title": "Aiphone5",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  },
  
  {
    "title": "Aiphone6",
    "image": "lllllll",
    "link": "llllll",
    "info":"llllll"
  }
]

如果我如上所示运行php代码,则json的o / p如上

标签: phparraysjsonwebserver

解决方案


我找到了这个答案

用这个

$array_data['Apple'][] = $extra;

代替

$array_data[] = $extra; 

推荐阅读