PHP using a string with multiple child keys as a lookup key for an associated array [duplicate]

StackOverflow https://stackoverflow.com/questions/22802132

  •  26-06-2023
  •  | 
  •  

Question

I would like a multiple child 'key' as a 'lookup' to get a object out of various associative arrays. For example:

$lookup_key = "['objects'][0]['object2']";

// this will be stored so when I need to get an object's value from various different arrays I can use these string to form a lookup key to get certain objects 

$object_array= array();
$object_array= ["objects"=>[["object1"=>"boot", "object2"=>"shoe"],"object"], "flowers"];

// using that key get the value
$object_value= $object_array->lookup($lookup_key);

Now does php have a method that already does this type of lookup or I suppose its an multidimensional key?

Any help would be great! Thanks in advance. This is part of an object lookup table.

Was it helpful?

Solution

I approached this in a slightly different way by storing a string of the objects then exploding that into an array from that travelling across that array to get the value:

$object_array= array();
$object_array= ["objects"=>[["object1"=>"boot", "object2"=>"shoe"],"object"], "flowers"];

$lookup=array();
$lookup_key="objects,0,object2";
$lookup=explode(',',$lookup_key);

$temp_object=array();
$new_object_array=array();
$new_object_array=$object_array;

$count=count($lookup);

for($i=0; $i<$count; $i++) {
    $temp_object=$new_object_array[$lookup[$i]];
    $new_object_array=$temp_object;
}
echo "\n value: $new_object_array";

As I was search for a quick implementation this seemed to be the best way within my time constraints and php lose variable casting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top