翻转/反转多维数组

时间:2015-06-02 08:00:04

标签: php arrays

我有一个想要反转/反转的多维数组。 我的数组在第一个索引中包含7天的日期作为日期。这些日子里面每个都有16个不同的记录。我希望将其转换为16个主要结果的结果,其中包括7天后的结果。 所以来自

'2015-04-28' => array(
        (int) 1 => (float) 1,
        (int) 2 => (float) 0.5,
        (int) 3 => (float) 0,
        (int) 4 => (float) 0,
        (int) 5 => (float) 1,
        (int) 6 => (float) 1,
        (int) 7 => (float) 0.66666666666667,
        (int) 8 => (float) 1,
        (int) 9 => (float) 0.66666666666667,
        (int) 10 => (float) 0.5,
        (int) 11 => (float) 1,
        (int) 12 => (float) 0.5,
        (int) 13 => (float) 1,
        (int) 14 => (float) 0,
        (int) 15 => (float) 0.5,
        (int) 16 => (float) 1
    ),


to 
 array(
                (int) 1 => array(
                    '2015-04-27' => (float) 1,
                    '2015-04-28' => (float) .67,
                    '2015-04-29' => (float) .5
                ),
                (int) 2 => array(
                    '2015-04-27' => (float) 1,
                    '2015-04-28' => (float) .67,
                    '2015-04-29' => (float) .5
                ),
                (int) 3 => array(
                    '2015-04-27' => (float) 1,
                    '2015-04-28' => (float) .67,
                    '2015-04-29' => (float) .5
                ),
                (int) 4 => array(
                    '2015-04-27' => (float) 1,
                    '2015-04-28' => (float) .67,
                    '2015-04-29' => (float) .5
                ),
            );

等等。是否有可用的PHP函数,或者我需要手动转换它吗?

1 个答案:

答案 0 :(得分:1)

一旦你掌握了关联数组,就不是很难了。 您可以创建一个新数组,并在循环中填充值,如下所示:

function transposeArray($arr) {
    $result = array();
    foreach ($arr as $mKey => $subArr) {
        foreach ($subArr as $sKey => $sVal) {
            $result[$sKey][$mKey] = $sVal;
        }
    }
    return $result;
}