【发布时间】:2018-10-20 19:08:57
【问题描述】:
我有一个对象数组,但在循环中它的行为类似于 PHP 引用。
我还在同一个结构中创建了一个数组,它可以正常工作。
我想在子项中添加一个名为“已处理”的键,在对象数组结构中,所有子项都在更新,但我只想更新特定项,如基于数组的示例。请参阅示例以进一步理解我的意思。
Click here to run this code in PHPFiddle
// OBJECT
$pool = [
1 => (Object)[
'id' => '1',
'title' => 'Pool 1'
],
2 => (Object)[
'id' => '2',
'title' => 'Pool 2'
],
];
$items = [
(Object)['id' => 1],
(Object)['id' => 2],
];
$vars = [];
foreach ($items as $i => $item) {
$vars[$i] = $item;
$vars[$i]->pool = $pool;
$vars[$i]->pool[$item->id]->processed = true;
}
// ARRAY
$pool1 = [
1 => [
'id' => '1',
'title' => 'Pool 1'
],
2 => [
'id' => '2',
'title' => 'Pool 2'
],
];
$items1 = [
['id' => 1],
['id' => 2],
];
$vars1 = [];
foreach ($items1 as $i1 => $item1) {
$vars1[$i1] = $item1;
$vars1[$i1]['pool'] = $pool1;
$vars1[$i1]['pool'][$item1['id']]['processed'] = true;
}
?>
<h4>
Object result
</h4>
<pre
<?php print_r($vars); ?>
></pre>
<h4>
Array result
</h4>
<pre
<?php print_r($vars1); ?>
></pre>
结果是
Object result
stdClass Object
(
[id] => 1
[pool] => Array
(
[1] => stdClass Object
(
[id] => 1
[title] => Pool 1
[processed] => 1
)
[2] => stdClass Object
(
[id] => 2
[title] => Pool 2
[processed] => 1
)
)
)
[1] => stdClass Object
(
[id] => 2
[pool] => Array
(
[1] => stdClass Object
(
[id] => 1
[title] => Pool 1
[processed] => 1
)
[2] => stdClass Object
(
[id] => 2
[title] => Pool 2
[processed] => 1
)
)
)
)
>
Array result
Array
(
[id] => 1
[pool] => Array
(
[1] => Array
(
[id] => 1
[title] => Pool 1
[processed] => 1
)
[2] => Array
(
[id] => 2
[title] => Pool 2
)
)
)
[1] => Array
(
[id] => 2
[pool] => Array
(
[1] => Array
(
[id] => 1
[title] => Pool 1
)
[2] => Array
(
[id] => 2
[title] => Pool 2
[processed] => 1
)
)
)
)
>
【问题讨论】:
-
是的,PHP 中的对象是通过引用传递的。你有什么问题?
-
我以为它就像一个数组,但我的错误。克隆解决了我的问题。谢谢。