Reputation: 295
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
}
Upvotes: 0
Views: 88
Reputation: 1302
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.
Upvotes: 2
Reputation: 71384
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.
Upvotes: 2