array_push不插入值

时间:2014-02-14 00:47:06

标签: php arrays loops

这是示例代码:

//$pieces is an stdClass object which has 4 elements the foreach loops through
$arr = array();
foreach($pieces as $piece)
{
     $piece->value = 1;
     array_push($arr, $piece);

     $piece->value = 3;
     array_push($arr, $piece);
}

问题在于它在我得到的结果中没有使用第一个array_push,就像它不存在一样:

Array
(
    [0] => stdClass Object
        (
             [piece] = 3
        )
    [1] => stdClass Object
        (
             [piece] = 3
        )
    [2] => stdClass Object
        (
             [piece] = 3
        )
    [3] => stdClass Object
        (
             [piece] = 3
        )
)

虽然[piece] = 1应该有额外的4个键。我做错了吗?

2 个答案:

答案 0 :(得分:1)

对象始终是引用。在尝试使用它之前,您需要clone该对象,就像它是两个不同的东西一样。

答案 1 :(得分:1)

您必须克隆$piece对象,您的代码目前将对$piece的引用保存到$arr。此代码段假定您需要阵列中两个$piece变体的实际副本。

$arr = array();
foreach($pieces as $piece)
{
     $first_clone = clone $piece;
     $first_clone->value = 1;
     array_push($arr, $first_clone);

     $second_clone = clone $piece;
     $second_clone->value = 3;
     array_push($arr, $second_clone);
}