web-dev-qa-db-fra.com

comment ajouter un élément au tableau au format json

J'utilise en utilisant seulement 1 données à insérer dans mon fichier json.

$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);

Voici donc à quoi ressemble mon fichier json. Je veux juste ajouter 1 joueur à la fin.

{ 

"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":"*"
            },

      ]
    }
  ] 
}

Ma question est, comment ajouter un joueur à la fin? Et je voudrais aussi savoir comment mettre à jour

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

dans le tableau de correspondance.

13
user2234992

Décodez simplement votre chaîne json, puis utilisez le tableau Push

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

Pour votre cas

    $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);

Vérifiez simplement la valeur de print_r ($ arr); J'espère que c'est ce que tu veux. :)

15
chandresh_cool

Ajout d'un autre joueur

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

Mise à jour des correspondances

premier tableau de correspondance

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

deuxième tableau de correspondance

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

sont maintenant de simples tableaux bidimensionnels avec des clés player1id, player2id et winner - il devrait être facile de les mettre à jour. Après cela, vous pouvez encoder le $tempArray retour à json.

7
slash197
<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>
2
sudheer suri

Dans Core PHP

si vous voulez un tableau sur JSON Response. alors vous pouvez aller avec ce code.

De manière très simple, vous pouvez utiliser ces étapes.

1) étape, vous devez convertir JSON en tableau en utilisant json_decode ().

2) utilisez la méthode array_merge () pour ajouter un nouveau tableau. si vous souhaitez ajouter un tableau.

$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 );

Production

{
    "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": ""
            }
        ]
    }
}
0
pankaj kumar