[英]adding json objects to array php
Im having a problem working with JSON objects and PHP. 我在处理JSON对象和PHP时遇到问题。 The Edited_Players JSON object can have one or more child objects as shown below Edited_Players JSON对象可以具有一个或多个子对象,如下所示
Here it is with 2 child objects 这是2个子对象
"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: 这是一个1个子对象:
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. 问题是当我执行以下代码时,如果Edited_Players JSON对象的大小为2,则for循环将执行两次,这是正确的。 BUT if the Edited_Players JSON object is of size 1 then the loop executes 6 times. 但是,如果Edited_Players JSON对象的大小为1,则循环执行6次。
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. 这是因为如果Edited_Players> 1则由数组填充,但如果= 1则仅对其中的单个对象进行计数。
how can make change so that the code sees {position,last_name,id,first_name,weight,height] as 1 object? 如何进行更改,以使代码将{position,last_name,id,first_name,weight,height]视为1个对象?
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 . 如果我理解这个问题,那么使用json_decode可能会更好。 This will allow you to access each return value as an object. 这将允许您将每个返回值作为一个对象进行访问。
The problem is in the constructed JSON. 问题出在构造的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. 我认为应该总是有一个数组包装一个或多个“ Edited_Players”对象,而在第二种情况下则没有,因此最终迭代了所提供的单个对象的属性。
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. 如果您无法控制JSON,则应检测Edited_Players
的值是数组还是对象,并相应地使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.