在PHP中,我有一个数组$test
。运行var_dump($test)
看起来像这样:
array(2) {
[0]=>
object(stdClass)#2 (6) {
["name"]=>
string(45) "Lorem"
["title"]=>
string(96) "Lorem ipsum"
}
[1]=>
object(stdClass)#3 (6) {
["name"]=>
string(41) "Ipsum"
["title"]=>
string(86) "Dolor sit amet"
}
}
现在我需要向url
个对象添加另一个字段($test
),如下所示:
array(2) {
[0]=>
object(stdClass)#2 (6) {
["name"]=>
string(45) "Lorem"
["title"]=>
string(96) "Lorem ipsum"
["url"]=>
string(86) "http://www.google.com"
}
[1]=>
object(stdClass)#3 (6) {
["name"]=>
string(41) "Ipsum"
["title"]=>
string(86) "Dolor sit amet"
["url"]=>
string(86) "http://www.stackoverflow.com"
}
}
我已尝试过foreach()
和$test->append('xxxxxxxx');
,但我遇到了错误。这真的不容易吗?我做错了什么?
答案 0 :(得分:7)
你很亲密:
foreach( $test as $t ) {
$t->url = "http://www.example.com";
}
当您真正处理append()
时,您似乎正在尝试使用ArrayObject
(stdClass object
的方法)。
答案 1 :(得分:1)
追加用于将整个对象附加到另一个对象。只需使用普通对象引用(obj-> value)来分配URL
$objectOne = new \stdClass();
$objectOne->name = 'Lorem';
$objectOne->title = 'Lorem ipsum';
$objectTwo = new \stdClass();
$objectTwo->name = 'Ipsum';
$objectTwo->title = 'Dolor sit amet';
$test = array(
0 => $objectOne,
1 => $objectTwo
);
$urls = array(
0 => 'http://www.google.com',
1 => 'http://www.stackoverflow.com'
);
$i = 0;
foreach ($test as $site) {
// Add url from urls array to object
$site->url = $urls[$i];
$i++;
}
var_dump($test);
输出:
array(2) {
[0]=>
object(stdClass)#1 (3) {
["name"]=>
string(5) "Lorem"
["title"]=>
string(11) "Lorem ipsum"
["url"]=>
string(21) "http://www.google.com"
}
[1]=>
object(stdClass)#2 (3) {
["name"]=>
string(5) "Ipsum"
["title"]=>
string(14) "Dolor sit amet"
["url"]=>
string(28) "http://www.stackoverflow.com"
}
}