标题很难到达,但基本上我正在尝试做的是从我的数据库中检索一些数据,并将其中的部分插入到两个数组中:
>第一个数组是一个常规有序数组,所以
$list = [
0 => ['id' => 'a', 'value' => 2],
1 => ['id' => 'b', 'value' => 4],
// etc
];
>第二个数组将使用对象的唯一id作为数组的键,所以
$map = [
'a' => ['id' => 'a', 'value' => 2],
'b' => ['id' => 'b', 'value' => 4],
// etc
];
但是,我希望$list和$map的实际内容通过引用链接,所以如果我更改一个,另一个会更新.
// update `a`'s value
$map['a']['value'] = 10;
// will echo "TRUE"
echo ($list[0]['value'] === 10 ? 'TRUE' : 'FALSE');
但是,我正在使用的代码不起作用,我可以看到原因,但不知道如何解决它.
这是我脚本中发生的一些伪代码:
// Sample data
$query_result = [
['id' => 'a', 'other_data' => '...'],
['id' => 'b', 'other_data' => '...'],
['id' => 'c', 'other_data' => '...'],
// etc
];
$list = [];
$map = [];
foreach ($query_result as $obj) {
// Problem is here, $temp_obj gets reassigned, rather than a new variable being created
$temp_obj = ['foreign_key' => $obj['id'], 'some_other_data' => 'abc', ];
// Try to have object that is inserted be linked across the two arrays
$list[] = &$temp_obj;
$map[$obj['id']] = &$temp_obj;
}
// Both will just contain my 3 copies of the last item from the query,
// in this case, `['id' => 'c', 'other_data' => '...'],`
var_dump($list);
var_dump($map);
这是一个非常简化的版本,但基本上是相同的.
因此,当我循环遍历我的对象并将它们添加到两个数组$list和$map时,如何添加这些对象以使它们成为彼此的链接?