Create two arrays, one index with index 0 and an identification index, with links connecting two

The name is hard to find here, but essentially what I am trying to do is take some data extracted from my database and paste their parts into two arrays:

  • The first array is an ordered array, therefore

    $list = [
      0 => ['id' => 'a', 'value' => 2],
      1 => ['id' => 'b', 'value' => 4],
      // etc  
    ];
    
  • And the second array will use the unique identifier of the object as keys for the array, therefore

    $map = [
      'a' => ['id' => 'a', 'value' => 2],
      'b' => ['id' => 'b', 'value' => 4],
      // etc  
    ];
    

However, I would like to see the actual content $listand $mapcommunicate via a link, so if I have to change it, the other is updated.

// update `a` value
$map['a']['value'] = 10;

// will echo "TRUE"
echo ($list[0]['value'] === 10 ? 'TRUE' : 'FALSE');

However, the code I use does not work, and I can understand why, but I'm not sure what to do to fix it.

Here are a few pseudo codes of what happens in my script:

<?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, , ?

+4
1

& :

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

All Articles