PHP循环遍历数组并追加到对象

时间:2017-07-17 10:11:16

标签: php arrays

我有像这样的对象数组;

Array
(
    [0] => stdClass Object
        (
            [Job] => stdClass Object
                (
                    [ID] => 123
                    [Name] => Foo
                 )
        )
    [1] => stdClass Object
        (
            [Job] => stdClass Object
                (
                    [ID] => 456
                    [Name] => BAR
                 )
        )
)

我需要遍历数组并向对象附加一些额外的信息,例如“状态”,但我有一些问题。

foreach($arrJobs as $key => $val) {

  $arrJobs[$key]->Job->Status = new StdClass;
  $arrJobs[$key]->Job->Status = $myStatus;

}

这似乎有效,但我收到以下警告;

  

警告:在......

中从空值创建默认对象

4 个答案:

答案 0 :(得分:2)

是的,先创建一个对象。您无法指定null的属性。这就是为什么你需要一个stdClass,php的通用空类的实例。

$arrJobs[$key] = new stdClass;
$arrJobs[$key]->foo = 1;

// And/or see below for 'nested' ...
$arrJobs[$key]->bar = new stdClass;
$arrJobs[$key]->bar->foo = 1;

答案 1 :(得分:1)

根据我对您的理解问题,您只需将属性附加到现有对象即可。 不要在循环中创建新对象

你只需要这个

foreach ($arrJobs as $obj)
{
    $obj->job->status = $myStatus;
}

请参阅完整代码:

<?php
$obj1 = new \stdClass();
$obj1->job = new \stdClass();
$obj1->job->id = 123;
$obj1->job->name = "foo";

$obj2 = new \stdClass();
$obj2->job = new \stdClass();
$obj2->job->id = 456;
$obj2->job->name = "bar";

$array = [$obj1,$obj2];

var_dump($array);
foreach ($array as $obj)
{
    $obj->job->status = "the status";
    //add any properties as you like dynamicly here
}
echo "<br>\nafter<br>\n";
var_dump($array);
exit;

现在$obj1$obj2有新属性'status',请参阅演示:(https://eval.in/833410

答案 2 :(得分:0)

for ($i = 0; $i < count($arrJobs); $i++)
{
    $arrJobs[$i]->Job->Status = new stdClass;
    // other operations
}

答案 3 :(得分:0)

试试这个,

<强> PHP

<?php
    // Sample object creation.
    $array = [];
    $array = [0 => (object) ['Job'=>(object) ['ID'=>123, 'Name' => 'Foo']]];

    foreach($array as $val) {
        $val->Job->Status = (object) ['zero' => 0,'one' => 1]; // Status 0 and 1.
    }

    echo "<pre>";
    print_r($array);
?>

<强>输出

Array
(
    [0] => stdClass Object
        (
            [Job] => stdClass Object
                (
                    [ID] => 123
                    [Name] => Foo
                    [Status] => stdClass Object
                        (
                            [zero] => 0
                            [one] => 1
                        )

                )

        )

)