[英]php unset in array foreach loop creates an object
I have a big JSON that looks something like this: 我有一个很大的JSON,看起来像这样:
{
"bracers": [
{
"id": "Bracers_208",
"name": "Unearthed Boon"
}
],
"offHand": [
{
"id": "Bracers_208",
"name": "Unearthed Boon"
},
{
"id": "Weapon123",
"name": "Some Weapon Boon"
},
{
"id": "Weapon456",
"name": "Some Other Weapon Boon"
}
],
"mainHand": [
{
"id": "Weapon123",
"name": "Some Weapon Boon"
}
]
}
I decode the JSON like this: 我这样解码JSON:
$itemDB = json_decode($json, true);
What I want to do now is to remove all entries from offHand
that are already in mainHand
. 我现在想做的是从
offHand
中删除所有已经在mainHand
中的mainHand
。 So I loop through both, compare the id
and unset()
the value if there's a match. 因此,我遍历了两者,如果有匹配项,则比较
id
和unset()
的值。
foreach($itemDB['offHand'] as $index => $item) {
foreach($itemDB['mainHand'] as $key => $weapon) {
if($item['id'] == $weapon['id']) {
unset($itemDB['offHand'][$index]);
}
}
}
Then I encode it again: 然后我再次编码:
$newJSON = json_encode($itemDB, JSON_PRETTY_PRINT);
The removal of duplicates works, but the offHand
array is changed into an object (or assoc array) that looks like this: 删除重复项是
offHand
,但是offHand
数组被更改为如下所示的对象(或assoc数组):
{
"bracers": [
{
"id": "Bracers_208",
"name": "Unearthed Boon"
}
],
"offHand": [
"0": {
"id": "Bracers_208",
"name": "Unearthed Boon"
},
"2": {
"id": "Weapon456",
"name": "Some Other Weapon Boon"
}
],
"mainHand": [
{
"id": "Weapon123",
"name": "Some Weapon Boon"
}
]
}
Why does this happen and how can I prevent it? 为什么会发生这种情况,如何预防呢?
Edit: Just to clarify, if I remove the unset
function and just do nothing inside that loops ( or just add a property to the objects), the numbered additional keys in the JSON aren't there and the JSON array is fine. 编辑:澄清一下,如果我删除了
unset
函数,并且在循环内什么也不做(或者只是向对象添加了一个属性),则JSON中没有编号的附加键,JSON数组就可以了。 That's why I concluded that unset
is causing this. 这就是为什么我得出这样的结论:
unset
造成的原因。
循环结束后,添加以下代码行以从offHand数组元素中删除键:
$itemDB['offHand'] = array_values($itemDB['offHand']);
As much a I think , by unset, you are removing a part of array, making it non sequential Thus it might be converted into object 我认为,通过未设置,您正在删除数组的一部分,使其不连续,因此可能会将其转换为对象
I guess the above line was bit unclear, so consider this example, 我猜上面的一行还不清楚,所以考虑这个例子,
function ep($f)
{
echo "<br><pre><code>";
print_r($f);
echo "</code></pre><br";
}
$t = array("a","b","c");
ep(json_encode($t));
unset($t[1]);
ep(json_encode($t));
Forget the function ep
.On line 1 , we declare a sequential array and print it, as it is sequential it prints as an array. 忘记函数
ep
。在第1行,我们声明一个顺序数组并打印它,因为它按顺序打印为数组。 On line 2, we break the sequence. 在第2行,我们中断了序列。 So printing it again , though it is an array, (*it maybe PHP's function does not know how to convert it) it printed as Object
因此,再次打印它(尽管它是一个数组)(*它的PHP函数可能不知道如何转换它),但将它打印为Object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.