PHP 将数据附加到数组对象


PHP append data to array 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"
  }
}

现在我需要向$test对象添加另一个字段(url),使其看起来像:

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');,但遇到错误。这难道不应该很容易做到吗?我做错了什么?

你很接近:

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

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

追加用于将整个对象附加到另一个对象。只需使用普通的对象引用(obj->值)来分配一个 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"
  }
}