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.

1

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You could also use array_reduce

$val = array_reduce($name, function($carry, $item) {
    return $carry[$item];
}, $people);

Comments

-1

looks like you just want:

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

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.