PHP将数据附加到数组对象

car*_*mba 0 php arrays object

在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"
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要向对象添加另一个field(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"
  }
}
Run Code Online (Sandbox Code Playgroud)

我试过foreach()$test->append('xxxxxxxx');,但我得到的错误.这真的不容易吗?我究竟做错了什么?

And*_*ion 7

你很亲密:

foreach( $test as $t ) {
    $t->url = "http://www.example.com";
}
Run Code Online (Sandbox Code Playgroud)

看起来你正在尝试使用append()(一种方法ArrayObject),当你真正处理一个stdClass object.

  • @Whymarrh正在努力;) (2认同)