How to send an array of objects in JSON format from PHP

后端 未结 6 2086
一向
一向 2020-12-31 12:59

New to php. I am trying to send JSON data to front end in name-value pair. I tried an example which I got here The following is my code fragment which sends the data in JSO

6条回答
  •  攒了一身酷
    2020-12-31 13:38

    Let's suppose we have this file structure without specific Objects inside :

      {
        "Subjects" : []
      }
    
    
    
    //Get your Json file and decode it 
    $json = file_get_contents('CdStore/Pagetest.json');
    $json_data = json_decode($json,true);
    
       //Specifiy your Objects like this
    $NewArray= array( 'Mathematics' => array(),'Physics' => array());
      //Push the new Objects  
    array_push($json_data['Pagess'],$NewArray); 
       //Then encode to json
    $array = json_encode($json_data); 
      //If you want to get the preview before saving
    print_r($array);  
    
     //Save your file
    file_put_contents('CdStore/Pagetest.json', json_encode($json_data));
    

    As result you have :

     {"Subjects":
         [
           {
            "Mathematics":[],
    
            "Physics":[]
    
             }
         ]
    
      }
    

提交回复
热议问题