3

I have the following array:

$people['men'] = [
    'first_name' => 'John',
    'last_name' => 'Doe'
];

And I have the following flat array:

$name = ['men', 'first_name'];

Now I want to create a function that "reads" the flat array and gets the value from the multidimensional array, based on the sequence of the elements of the flat array.

function read($multidimensionalArray,$flatArray){
    // do stuff here
}

echo read($people,$name); // must print 'John'

Is this even possible to achieve? And which way is the way to go with it? I'm really breaking my head over this. I have no clue at all how to start.

Thanks in advance.

Sam Leurs
  • 480
  • 4
  • 20

4 Answers4

3

This should to the trick:

<?php

$people['men'] = [
    'first_name' => 'John',
    'last_name' => 'Doe'
];
$name = ['men', 'first_name'];

echo read($people,$name);

function read($multidimensionalArray,$flatArray){
    $cur = $multidimensionalArray;
    foreach($flatArray as $key)
    {
        $cur = $cur[$key];
    }
    return $cur;
}

Link: https://3v4l.org/96EnQ

Be sure to put some error checking in there (isset and the likes)

ccKep
  • 5,786
  • 19
  • 31
1

You can use a recursive function to do this.

function read(&$array, $path) {

    // return null if one of the keys in the path is not present
    if (!isset($array[$key = array_shift($path)])) return null;

    // call recursively until you reach the end of the path, then return the value
    return $path ? read($array[$key], $path) : $array[$key];
}

echo read($people, $name);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

You could also use array_reduce

$val = array_reduce($name, function($carry, $item) {
    return $carry[$item];
}, $people);
Philipp
  • 15,377
  • 4
  • 35
  • 52
-1

looks like you just want:

echo $multidimensionalArray[$flatArray[0]][$flatArray[1]];
Anon
  • 1