Fill a multi-dimensional array from an array of keys and a single value

房东的猫 提交于 2019-12-13 04:42:07

问题


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

回答1:


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.




回答2:


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"];


来源:https://stackoverflow.com/questions/22116640/fill-a-multi-dimensional-array-from-an-array-of-keys-and-a-single-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!