0

在 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()and $test->append('xxxxxxxx');,但遇到错误。这不应该很容易做到吗?我究竟做错了什么?

4

2 回答 2

7

你很接近:

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

当您真正append()处理.ArrayObjectstdClass object

于 2013-09-08T13:00:36.413 回答
1

Append 用于将整个对象附加到另一个对象。只需使用普通对象引用 (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"
  }
}
于 2013-09-08T13:06:44.183 回答