在数组foreach循环中未设置php创建对象 [英] php unset in array foreach loop creates an object
问题描述
我有一个看起来像这样的大JSON:
I have a big JSON that looks something like this:
{
"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"
}
]
}
我这样解码JSON:
$itemDB = json_decode($json, true);
我现在要做的是从offHand
中删除所有已经在mainHand
中的条目.因此,我遍历了两者,如果有匹配项,请比较id
和unset()
的值.
What I want to do now is to remove all entries from offHand
that are already in mainHand
. So I loop through both, compare the id
and unset()
the value if there's a match.
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);
删除重复项是可行的,但是offHand
数组被更改为如下所示的对象(或assoc数组):
The removal of duplicates works, but the offHand
array is changed into an object (or assoc array) that looks like this:
{
"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?
只是为了澄清一下,如果我删除了unset
函数,并且在循环内什么也不做(或者只是向对象添加了一个属性),则JSON中没有编号的附加键,并且JSON数组就可以了.这就是为什么我得出结论unset
导致了这一点的原因.
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. That's why I concluded that unset
is causing this.
推荐答案
循环结束后,添加以下代码行以从offHand数组元素中删除键:
After you're loop ends, add the following line of code to remove the keys from the offHand array element:
$itemDB['offHand'] = array_values($itemDB['offHand']);
这篇关于在数组foreach循环中未设置php创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!