这看起来很简单,但我无法弄清楚。我有一个json_decoded的现有对象数组。我需要迭代这些对象,为每个对象附加一个新数组,然后将整个数组重新组合在一起。我无法将新数组添加到正确的位置。
["bar", "baz" ...]
以下是我开始使用的其中一个对象的示例(当然在function appendToArray($arrayOfObjects) {
$newArray = array();
foreach ($arrayOfObjects as $object) {
echo "<pre>".print_r($object, true)."</pre>";
$newItems = array('item1', 'item2', 'item3');
$moreItems = array('more1', 'more2', 'more3');
$newObject = array();
$newObject["newItems"] = $newItems;
$newObject["moreItems"] = $moreItems;
$rebuiltObject = array();
array_push($rebuiltObject, $object);
$rebuiltObject['new_stuff'] = $newObject;
// $rebuiltObject[0]['new_stuff'] = $newObject;
array_push($newArray, $newObject);
}
return $newArray;
}
之后:
json_decode
完成后,我想要的是:
0 => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
)
但我得到的是:
0 => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
[new_stuff] => Array
(
[newItems] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
[moreItems] => Array
(
[0] => more1
[1] => more2
[2] => more3
)
)
)
注意[0] => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
),
[new_stuff] => Array
(
[newItems] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
[moreItems] => Array
(
[0] => more1
[1] => more2
[2] => more3
)
)
)
如何在原始对象之外。我需要进去。我尝试过的其他一切都崩溃了,而且我完全没有想法。谁能看到我怎么做到这一点?谢谢!
答案 0 :(得分:1)
您的解决方案是一个字符串:
$object->new_stuff = $newObject;
因为每个$object
都是对象而不是数组。向对象添加新属性是通过->
完成的,而不是[]
。
完整代码:
function appendToArray($arrayOfObjects) {
foreach ($arrayOfObjects as $object) {
echo "<pre>".print_r($object, true)."</pre>";
$newItems = array('item1', 'item2', 'item3');
$moreItems = array('more1', 'more2', 'more3');
$newObject = array();
$newObject["newItems"] = $newItems;
$newObject["moreItems"] = $moreItems;
$object->new_stuff = $newObject;
}
return $arrayOfObjects;
}
答案 1 :(得分:1)
您可以array_walk并更改对象:
getComponent