简体   繁体   中英

adding json objects to array php

Im having a problem working with JSON objects and PHP. The Edited_Players JSON object can have one or more child objects as shown below

Here it is with 2 child objects

"Team_Updates": {
    "Edited_Players": [
        {
            "position": "flanker",
            "last_name": "mowbrayfg",
            "id": 3,
            "first_name": "fchris",
            "weight": "weight",
            "height": "high"
        },
        {
            "id": 4,
            "last_name": "gg",
            "position": "gg",
            "first_name": "ffgyvvyvy",
            "height": "cttvyv",
            "weight": "gg"
        }
    ]
},

Here it is with 1 single child object:

Team_Updates": {
    "Edited_Players": 
        {
            "position": "flanker",
            "last_name": "mowbrayfg",
            "id": 3,
            "first_name": "fchris",
            "weight": "weight",
            "height": "high"
        }
               }

The problem is when I execute the below code, if the Edited_Players JSON object is of size 2 then the for loop will execute twice and that is correct. BUT if the Edited_Players JSON object is of size 1 then the loop executes 6 times.

This is because if Edited_Players > 1 then it is populated by an array but if = 1 then it just counts the single objects within.

how can make change so that the code sees {position,last_name,id,first_name,weight,height] as 1 object?

if(isset($editedPlayersObj)){

    $epIDArray = array();
    $epFnameArray = array();
    $epSnameArray = array();
    $epHieghtArray = array();
    $epWeightArray = array();
    $epPosArray = array();

    for ($x=0; $x<count($editedPlayersObj); $x++)
      {
        $epFnameArray[$x] = $editedPlayersObj[$x]['first_name'];
        $epSnameArray[$x] = $editedPlayersObj[$x]['last_name'];
        $epIDArray[$x] = $editedPlayersObj[$x]['id'];
        $epHieghtArray[$x] = $editedPlayersObj[$x]['weight'];
        $epWeightArray[$x] = $editedPlayersObj[$x]['height'];
        $epPosArray[$x] = $editedPlayersObj[$x]['position'];

        // insert into database the above 
      } 

If I understand the question, you might have better luck using json_decode . This will allow you to access each return value as an object.

The problem is in the constructed JSON. I would think that there should ALWAYS be an array wrapping one or more `Edited_Players" object(s). In your second case there is not, you so end up iterating the properties of the single object provided.

If you have no control over the JSON, then you should detect whether the value to Edited_Players is an array or an object and work with it accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM