创建两个数组,一个0索引,另一个ID索引,引用连接两个



标题很难到达这里,但是从本质上讲,我要做的就是从数据库中获取一些数据,然后将其部分插入两个数组:

  1. 第一个数组是常规订购的数组,所以

    $list = [
      0 => ['id' => 'a', 'value' => 2],
      1 => ['id' => 'b', 'value' => 4],
      // etc  
    ];
    
  2. ,第二个数组将使用对象的唯一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');

但是,我使用的代码无法正常工作,我可以明白为什么,但不确定该如何解决。

这是我脚本中发生的事情的一些伪代码:

<?php
// 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时,我该如何添加这些对象,以便它们彼此链接?

只需在您的代码中删除&

$list[] = $temp_obj;  
$map[$obj['id']] = $temp_obj;

最新更新