3

I'm not sure how to call this, and I can't find what I'm looking for because I must be looking for the wrong keywords, so even the right search term would help me out here:

I have a $map array and a $data array. The $data array is a dynamic array based on a xml that is parsed. Simplified Example:

$data = array('a' => array(0=> array('hello'=>'I want this data')));

$map = array('something' => 'a.0.hello');

Now I'd like to set $test to the value of $data['a']['0']['hello'] by somehow navigating there using $map['something']. The idea behind this is to create a mapping array so that no code changes are required if the xml format is to be changed, only the mapping array. Any help in the good direction is very much appreciated :)

2
  • are you searching for the value of something to navigate the I want this data Commented May 30, 2016 at 9:32
  • Can you be more specific on what exactly you need? Do you want something to point to a string? Maybe make a function which explodes the string and uses its elements as index(s) for the other array?! Commented May 30, 2016 at 9:34

2 Answers 2

3
// Set pointer at top of the array 
$path = &$data;
// Asume that path is joined by points
foreach (explode('.', $map['something']) as $p) 
   // Make a next step
   $path = &$path[$p];
echo $path; // I want this data
Sign up to request clarification or add additional context in comments.

5 Comments

that no code changes are required if the xml format is to be changed, only the mapping array - i understood it so
@FrayneKonok Maybe, difficult to write such code :)
I think the OP want to create the map array from data array.
Splash had it right, turns out I was thinking way to complicated!
Read there - php.net/manual/en/language.references.php and ask if you still have a question
1

There's not really a good way to programmatically access nested keys in arrays in PHP (or any other language I can think of, actually).

function getDeepValue(&$arr, $keys) {
  if (count($keys) === 0)
    return $arr;
  else
    return getDeepValue($arr[$keys[0]], array_slice($keys, 1));
}

$data = ['a' => [0=> ['hello'=>'I want this data']]];
$map = ['something' => getDeepValue($data, ['a', '0', 'hello'])];

var_dump($map);

// array(1) {
//   ["something"]=>
//   string(16) "I want this data"
// }

If you want to use the string of keys, just use

getDeepValue($arr, explode('.', 'a.0.hello'))

If that's a common operation you have to do, you could add another layer of abstraction that accepts string-based lookup of deep values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.