从值数组生成多维数组

时间:2014-03-28 20:06:21

标签: php arrays multidimensional-array

我有一个数组,其中的键描述了多维数组中的位置,如:

array(
        '3728:baskets:4839:1' => 'apple',
        '3728:baskets:4839:2' => 'orange',
        '3728:baskets:4920:1' => 'cherry',
        '3728:baskets:4920:2' => 'apple',
        '9583:baskets:4729:1' => 'pear',
        '9583:baskets:4729:2' => 'orange',
        '9583:baskets:6827:1' => 'banana',
        '9583:baskets:6827:2' => 'pineapple',
);

我想将此数组传递给一个函数,该函数根据":"分隔的键中的各个部分生成多维数组。生成的数组应如下所示:

array(
    3728 => array(
        'baskets' => array(
            4839 => array(
                1 => 'apple',
                2 => 'orange',
            ),
            4920 => array(
                1 => 'cherry',
                2 => 'apple',
            ),
        ),
    ),
    9583 => array(
        'baskets' => array(
            4729 => array(
                1 => 'pear',
                2 => 'orange',
            ),
            6827 => array(
                1 => 'banana',
                2 => 'pineapple',
            ),
        ),
    ),
);

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

function array_createmulti($arr) {
    // The new multidimensional array we will return
    $result = array();
    // Process each item of the input array
    foreach ($arr as $key => $value) {
        // Store a reference to the root of the array
        $current = &$result;
        // Split up the current item's key into its pieces
        $pieces = explode(':', $key);
        // For all but the last piece of the key, create a new sub-array (if
        // necessary), and update the $current variable to a reference of that
        // sub-array
        for ($i = 0; $i < count($pieces) - 1; $i++) {
            $step = $pieces[$i];
            if (!isset($current[$step])) {
                $current[$step] = array();
            }
            $current = &$current[$step];
        }
        // Add the current value into the final nested sub-array
        $current[$pieces[$i]] = $value;
    }
    // Return the result array
    return $result;
}

答案 1 :(得分:0)

它会比之前的回答更快:

function formatMyData($data)
{
    $res = array();
    foreach($data as $key => $value) {
        list($a, $b, $c, $d) = explode(':', $key);
        if (!isset($res[$a])) {
            $res[$a] = array(
                $b => array(
                    $c => array(
                        $d => $value
                    )
                )
            );
        }
        else if (!isset($res[$a][$b])) {
            $res[$a][$b] = array(
                $с => array(
                    $d => $value
                )
            );
        }
        else if (!isset($res[$a][$b][$c])) {
            $res[$a][$b][$c] = array(
                $d => $value
            );
        } else {
            $res[$a][$b][$c][$d] = $value;
        }
    }

    return $res;
}

See in action