15

I am using using just 1 data to insert in my json file.

$data=$_POST['myusernamer'];

$inp = file_get_contents('7players.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('7players.json', $jsonData);

So this is how my json file looks. I just want to add 1 player at the end.

{ 

"players":[
   {

        "name":"Moldova",
        "image":"/Images/Moldova.jpg",
        "roll_over_image":"tank.jpg"
   },
   {

        "name":"Georgia",
        "image":"/Images/georgia.gif",
        "roll_over_image":"tank.jpg"
   },
   {

        "name":"Belarus",
        "image":"/Images/Belarus.gif",
        "roll_over_image":"tank.jpg" 
   },
   {

        "name":"Armenia",
        "image":"/Images/armenia.png",
        "roll_over_image":"tank.jpg"
   },
   {

        "name":"Kazahstan",
        "image":"/Images/kazahstan.gif",
        "roll_over_image":"tank.jpg"
   },
   {

        "name":"Russia",
        "image":"/Images/russia.gif",
        "roll_over_image":"tank.jpg"
   },
  ],


"games" : [ 

    { 

    "matches" : [ 

            {

            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },

            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },

            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },

            {
            "player1id":"*",
            "player2id":7,
            "winner":"*"
            },

            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },

            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },

            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            }
        ]
       },

    {

    "matches" : [

            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },
            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },
            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },
            {
            "player1id":"*",
            "player2id":7,
            "winner":"*"
            },
            {           
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },
            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },
            {
            "player1id":"*",
            "player2id":"*",
            "winner":"*"
            },

      ]
    }
  ] 
}

My question is, how do I add player at the end? And I would also like to know how to update

player1id":"*",
"player2id":"*",
"winner":"

in the match array.

4

5 回答 5

18

只需解码您的 json 字符串,然后使用数组推送

$tempArray = json_decode($jsonstring, true);
array_push($tempArray, $your_data);

对于您的情况

    $str = '{ 

"players":[
   {

        "name":"Moldova",
        "image":"/Images/Moldova.jpg",
        "roll_over_image":"tank.jpg"
   },
   {

        "name":"Georgia",
        "image":"/Images/georgia.gif",
        "roll_over_image":"tank.jpg"
   } ]}';


 $arr = json_decode($str, true);
 $arrne['name'] = "dsds";
 array_push( $arr['players'], $arrne );
 print_r($arr);

只需检查 print_r($arr); 的值 我希望这是你想要的。:)

于 2013-04-24T05:32:53.117 回答
9

添加其他玩家

$tempArray = json_decode($inp, true);
array_push($tempArray['players'], array('name' => $data['username'], 'image' => $data['userimage'], 'roll_over_image' => 'tank.jpg'));

更新比赛

第一个匹配数组

$tempArray['games'][0]['matches'];

第二个匹配数组

$tempArray['games'][1]['matches'];

现在是带有键的简单二维数组player1idplayer2id并且winner- 应该很容易更新这些。之后,您可以将$tempArray回编码为 json。

于 2013-04-24T05:35:32.117 回答
2
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
    <?php
       //first copy your json data  data.json
        $str = file_get_contents('data.json');//get contents of your json file and store it in a string,bro small suggestion never keep any JSON data in ur html file its not safe.always keep json data in external file.
        $arr = json_decode($str, true);//decode it
         $arrne['players'] = "sadaadad";
         $arrne['image'] = "sadaadad";
         $arrne['roll_over_image'] = "sadaadad";
         array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
         $str = json_encode($arr);
        //now send evrything to ur data.json file using folowing code
         if (json_decode($str) != null)
           {
             $file = fopen('data.json','w');
             fwrite($file, $str);
             fclose($file);
           }
           else
           {
             //  invalid JSON, handle the error 
           }

        ?>
</body>

于 2016-08-23T01:51:52.030 回答
2

在核心 PHP 中

如果您想要 JSON 响应上的数组。那么您可以使用此代码。

很简单的方法,你可以使用这些步骤。

1) 步骤您必须使用json_decode()将 JSON 转换为数组。

2) 使用 array_merge() 方法添加新数组。如果您有兴趣添加一个数组。

$staff =  json_decode($staffRes ,true);
$driver = ["helpers"=>[id=>1,name=>hep1],[id=>2,name=>hep2]]
$profile= array_merge($staff ,$driver );

在 Laravel 中

$staff =  collect($staffRes)->toArray() ; // json() also work here.
$driver = ["helpers"=>[id=>1,name=>hep1],[id=>2,name=>hep2]]
$profile= array_merge($staff ,$driver );

输出

{
    "error": 0,
    "errmsg": "",
    "response": {
        "id": "NlF4VDMrdEoxM2RCUWkxUE92c29tZz09",
        "type": "DRIVER",
        "driver_name": "Ravi Kumar",     
        "route_name": "Barasat Dak Bungalow",
        "helpers": [
            {
                "helper_id": "K09NTlpHMStiNGlKSGZNMUIyWlAxZz09",
                "helper_name": "Arvind Kumar",
                "helper_mobile": "7777777775",
                "helper_alt_mobile": "7777777777",
                "birth_date": "01-10-2000",
                "address": "Bongaon",
                "id_proof": "123456789-WB",
                "licence_no": null,
                "experience": "2-year",
                "helper_photo":""
            },
            {
                "helper_id": "K29la21vY0VnMTZ5cFY2MU02cm1ZUT09",
                "helper_name": "SUBIR DAS",
                "helper_mobile": "5555555555",
                "helper_alt_mobile": "5555555554",
                "birth_date": "30-10-2019",
                "address": "610/8, ....",
                "id_proof": "NA",
                "licence_no": "NA",
                "experience": "2 years",
                "helper_photo": ""
            }
        ]
    }
}
于 2019-10-30T10:10:20.597 回答
0

使用这个 php 代码

 <?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 Posted 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"],  
                );  
                $array_data[] = $extra;  
                $products['products']=$array_data[];
                $final_data = json_encode($products);  
                if(file_put_contents('myfile.json', $final_data))  
                {  
                     $message = "<label class='text-success'>Added Successfully</p>";  
                }  
           }  
           else  
           {  
                $error = 'JSON File not exits';  
           }  
      }  
 }  
 ?>  
于 2020-06-24T07:16:32.250 回答