Fill a multi-dimensional array from an array of ke

2019-09-17 22:18发布

Is there an elegant way to turn an array into multi-dimensional keys and add in a value ?

$value = "You found the giant!"
$keys = array("fee", "fi", "fo", "fum");

$output[ flipster( $keys ) ] = $value; 
// $output['fee']['fi']['fo']['fum'] = "You found the giant!";

I wrote this function, which works & does what I need it to do, but I don't think it's the best solution...

function flipster( $array, $value ) {
    $out = array();
    $key = $array[0];
    array_shift( $array );

    if( count( $array ) > 0 ) {
        $out[ $key ] = flipster( $array, $value );  
    } else {
        $out[ $key ] = $value;
    }

    return $out;
}

In the end, I'm getting my "fee" and "fi" from a loop, so in the loop I'm doing something like this to create a new array:

$out = array_merge_recursive($out, flipster( $keys, $value ) );

2条回答
Animai°情兽
2楼-- · 2019-09-17 22:39
function flipster( array &$target, array $keys, $value ) {
    if(empty($keys)){
        return false;
    }

    $ref = &$target;
    foreach($keys as $key){
        if(!isset($ref[$key])){
            $ref[$key] = array();
        }
        $ref = &$ref[$key];
    }
    $ref = $value;

    return true;
}

$bucket = array();
flipster($bucket, array('x', 'y', 'z'), 'test1');
flipster($bucket, array('x', 'y', 'a'), 'test2');
flipster($bucket, array('a', 'b', 'c'), 'test3');
flipster($bucket, array('a', 'b', 'd'), 'test4');
flipster($bucket, array('a', 'c', 'e'), 'test5');
var_dump($bucket);

Try this on for size. Can combine multiple flips into the same array(). Makes it easy for you to build deep array trees. It uses a reference for deep array building, not a recursive function.

查看更多
The star\"
3楼-- · 2019-09-17 22:52

How about this using recursiveness:

function flipster( $arr, $value ) {
    if(count($arr)==1){
        return array($arr[0] => $value);
    }

    return array(array_shift($arr) => flipster( $arr, $value ));
}
$value = "You found the giant!";
$keys = array("fee", "fi", "fo", "fum");

$output = flipster( $keys, $value );
echo $output["fee"]["fi"]["fo"]["fum"];
查看更多
登录 后发表回答