jwebdev
jwebdev

Reputation: 113

How to map array depth?

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 :)

Upvotes: 3

Views: 359

Answers (2)

splash58
splash58

Reputation: 26153

// 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

Upvotes: 3

Mulan
Mulan

Reputation: 135327

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.

Upvotes: 1

Related Questions