从值数组生成多维数组



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

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

任何想法?

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

会比之前的答案更快:

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

实际操作

相关内容

  • 没有找到相关文章

最新更新