1

I've been hitting my head on this problem for some time now. I am working on a piece of software that creates a tree from a MySQL result checking for changes between each row to decide where in the tree to put the new data.

I'm now at a dead end while trying to understand how I can dynamically tell PHP to address different parts of my array.

I though about using variable variables but it doesn't seem to be working. To make my life easier I tried to set up a test file in which to test this behavior and this is the result...

$array = [
    0 => [
        "name" => "test"
    ],
    1 => [
        "name" => "test",
        "data" => [
            "content" => 5
        ]
    ]
];

$ref = 'array["1"]["name"]';

echo $ref."\n";
echo $$ref;

Output

array["1"]["name"] 
Notice: Undefined variable: array["1"]["name"] in P:\xampp\htdocs\assets\php\test.php on line 23

I was instead expecting something like test.

I would also like to mention that I've tried the ${} method but I doesn't affect the array, but instead adds the data to another variable those rare times it doesn't output an error.

Anyone can help? Thanks!

Francesco
  • 429
  • 4
  • 12

1 Answers1

0

after thinking about the problem once again I came up with a work-around to achieve the intended result. I decided to use references make with &$var.

I, so, decided to tweak the code to create an array of each step to do to arrive at the intended location, instead of a string. Example follows:

// Old method
$ref = 'array["1"]["name"];

// New method
$ref = ["1", "name"];

The code then follows by cycling through the array referencing the original array but slowly deeper...

// Referencing the original array
$referencedArray = &$array;

// Going one step at the time inside the nested array
foreach ($ref as $k => $v) {
   $referencedArray = &$referencedArray[$rav];
}

I believe this solution could fit my case, but if you have any suggestions please let me know.

Francesco
  • 429
  • 4
  • 12