首页 > 解决方案 > 使用 PHP 将数据附加到 JSON 文件的顶部

问题描述

我正在使用 PHP 表单将数据附加到 JSON 文件,但现在它将新数据添加到 JSON 文件的底部

我想将新数据添加到 JSON 文件的顶部而不是底部。

这是我用来将数据附加到 JSON 的我的 PHP 代码。

<?php  
 $message = '';  
 $error = '';  
 if(isset($_POST["submit"]))  
 {  
      if(empty($_POST["name"]))  
      {  
           $error = "<label class='text-danger'>Enter Name</label>";  
      }  
      else if(empty($_POST["author"]))  
      {  
           $error = "<label class='text-danger'>Enter Author</label>";  
      }  
      else if(empty($_POST["category"]))  
      {  
           $error = "<label class='text-danger'>Enter Thumbnail</label>";  
      }  
      else if(empty($_POST["url"]))  
      {  
           $error = "<label class='text-danger'>Enter URL</label>";  
      }  
      else  
      {  
          if(file_exists('wallpaper.json'))  
          {  
               $current_data = file_get_contents('wallpaper.json');  
               $array_data = json_decode($current_data, true);  
               $extra = array(  
                    'name'               =>     $_POST['name'],  
                    'author'          =>     $_POST["author"],  
                    'category'     =>     $_POST["category"],  
                    'url'     =>     $_POST["url"]  

               );  
               $array_data[] = $extra;  
               $final_data = json_encode($array_data);  
               if(file_put_contents('wallpaper.json', $final_data))  
               {  
                    $message = "<label class='text-success'>File Appended Success fully</p>";  
               }  
          }  
          else  
          {  
               $error = 'JSON File not exits';  
          }  
     }  
 }
 ?>

这是 wallpaper.JSON 目前它添加这样的数据 -

[
  {
    "name": "Old Code",
    "author": "Old Code",
    "category": "Old Code",
    "url": "https://wallpaperaccess.com/full/11851.jpg"
  },
  {
    "name": "New Code",
    "author": "New Code",
    "category": "New Code",
    "url": "https://wallpaperaccess.com/full/11851.jpg"
  }
]

我想要这样-

[
  {
    "name": "New Code",
    "author": "New Code",
    "category": "New Code",
    "url": "https://wallpaperaccess.com/full/11851.jpg"
  },
  {
    "name": "Old Code",
    "author": "Old Code",
    "category": "Old Code",
    "url": "https://wallpaperaccess.com/full/11851.jpg"
  }
]

标签: php

解决方案


那么你可以在你的用例中使用 use array_reverse 但我会做另一种方法

$array_data[] = $extra;  
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);

但更好的方法是使用 array_unshift

array_unshift($array_data, $extra);

来源:https ://www.php.net/manual/en/function.array-unshift.php


推荐阅读