Maxime Pacary
Maxime Pacary

Reputation: 23041

Getting a value into multidimensional array from a list of indexes (array too)

I'm looking for a nice way of doing the magicFunction():

$indexes = array(1, 3, 0);

$multiDimensionalArray = array(
  '0',
  array('1-0','1-1','1-2',array('2-0','2-1','2-2')),
  array('1-4','1-5','1-6')
);

$result = magicFunction($indexes, $multiDimensionalArray);

// $result == '2-0', like if we did $result = $multiDimensionalArray[1][3][0];

Thanks.

Upvotes: 1

Views: 130

Answers (6)

Maxime Pacary
Maxime Pacary

Reputation: 23041

My own attempt ; found it simpler by not doing it recursively, finally.

function magicFunction($arrayIndexes, $arrayData)
{
    if (!is_array($arrayData))
        throw new Exception("Parameter 'arrayData' should be an array");

    if (!is_array($arrayIndexes))
        throw new Exception("Parameter 'arrayIndexes' should be an array");

    foreach($arrayIndexes as $index)
    {
        if (!isset($arrayData[$index]))
            throw new Exception("Could not find value in multidimensional array with indexes '".implode(', ', $arrayIndexes)."'");

        $arrayData = $arrayData[$index];
    }

    return $arrayData;
}

Exceptions may be somewhat "violent" here, but at least you can know exactly what's going on when necessary.

Maybe, for sensitive hearts, a third $defaultValue optional parameter could allow to provide a fallback value if one of the indexes isn't found.

Upvotes: 0

hakre
hakre

Reputation: 197775

You can just step trough based on your keys (no need to do any recursion, just a simple foreach):

$result = &$multiDimensionalArray;
foreach($indexes as $index)
{
    if (!isset($result[$index]))
        break; # Undefined index error

    $result = &$result[$index];
}

If you put it inside a function, then it won't keep the reference if you don't want to. Demo.

Upvotes: 2

kapa
kapa

Reputation: 78681

This is a recursive version. Will return null if it cannot find a value with the given index route.

function magicFunction($indexes, $array) {
    if (count($indexes) == 1) {
        return isset($array[$indexes[0]]) ? $array[$indexes[0]] : null;
    } else {
        $index=array_shift($indexes);
        return isset($array[$index]) ? magicFunction($indexes, $array[$index]) : null;
    }
}

Upvotes: 2

Catalin
Catalin

Reputation: 868

Try this :P

function magicFunction ($indexes,$mdArr){
    if(is_array($mdArr[$indexes[0]] && $indexes)){
        magicFunction (array_slice($indexes,1),$mdArr[$indexes[0]]);
    }
    else {
        return  $mdArr[$indexes[0]];
    }
}

Upvotes: 0

halfdan
halfdan

Reputation: 34214

You can solve this recursively.

$indexes = array(1, 3, 0);

$multiDimensionalArray = array(
  '0',
  array('1-0','1-1','1-2',array('2-0','2-1','2-2')),
  array('1-4','1-5','1-6')
);

$result = magicFunction($indexes, $multiDimensionalArray);

function magicFunction($indices, $array) {
        // Only a single index is left
        if(count($indices) == 1) {
                return $array[$indices[0]];
        } else if(is_array($indices)) {
                $index = array_shift($indices);
                return magicFunction($indices, $array[$index]);
        } else {
                return false; // error
        }
}

print $result;

This function will go down the $multiDimensionalArray as long as there are indices available and then return the last value accesses by the index. You will need to add some error handling though, e.g. what happens if you call the function with $indexes = array(1,2,3,4);?

Upvotes: 2

Aleks G
Aleks G

Reputation: 57316

I think something like this should do the trick for you.

function magicFuntion($indexes, $marray)
{
    if(!is_array($indexes) || count($indexes) == 0 || !is_array($marray))
        return FALSE;

    $val = '';
    $tmp_arr = $marray;
    foreach($i in $indexes) {
        if(!is_int($i) || !is_array($tmp_arr))
            return FALSE;
        $val = $tmp_arr[$i];
        $tmp_arr = $tmp_arr[$i];
    }

    return $val;
}

Upvotes: 1

Related Questions