romellem
romellem

Reputation: 6491

Creating two arrays, one 0-indexed and the other ID indexed, with references connecting the two

Title is hard to get here, but essentially what I'm trying to do is take some data retrieved from my database, and insert portions of it into two arrays:

  1. First array is a regular ordered array, so

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

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

However, I'd like the actual contents of $list and $map to be linked via reference, so if I change one, the other gets updated.

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

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

However, the code I'm using isn't working, and I can see why, but not sure what to do to fix it.

Here is some pseudocode of what is kind of happening 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);

This is a very simplified version of what is going on but basically it is the same.

So, as I'm looping through my objects and adding them to two arrays, $list and $map, how can I add those objects so they are links to one another?

Upvotes: 4

Views: 52

Answers (1)

Daoud Taha
Daoud Taha

Reputation: 11

Just delete the & in your code like this:

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

Upvotes: 1

Related Questions