PHP翻转多维数组不起作用

时间:2013-04-02 18:25:47

标签: php arrays recursion flip

我想出了这段代码:

function multiArrayFlip($array)
{
    $arrayCount = count($array);
    if ($arrayCount != count($array, COUNT_RECURSIVE)) 
    {
        foreach($array as $key => $value)
        {
            if (is_array($value))
            {
                $array[$key] = multiArrayFlip($value);
            }
        }
    }
    else
    {
      array_flip($array);
    }   

    return $array;
}

但它不起作用。 它返回未更改的数组。这里是数组数据样本:

    Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [zip] => 02135
                        [hispanic_percent] => 7.4
                        [white_percent] => 73.1
                        [black_percent] => 4.2
                        [native_american_percent] => 0
                    )

            )

        [1] => Array
            (
                [0] => Array
                    (
                        [zip] => 02135
                        [school_number] => 1
                        [school_name] => ANOTHER COURSE TO COLLEGE
                        [school_address] => 20 WARREN STREET BRIGHTON MA 02135
                        [contact_number] => 617-635-8865
                        [start_grade] => 9TH GRADE
                        [reduced_lunch_students_count] => 8
                        [reduced_lunch_students_percent] => 120
                        [free_or_reduced_lunch_students_count] => 53
                        [free_or_reduced_lunch_students_percent] => 0
                    )
)
)

2 个答案:

答案 0 :(得分:1)

您必须将array_flip函数的返回值重新分配给$ array变量才能工作。

答案 1 :(得分:1)

您需要修改您的功能才能正常工作。在array_flip

之后重新分配值
function multiArrayFlip($array)
{
    $arrayCount = count($array);

    if ($arrayCount != count($array, COUNT_RECURSIVE)) 
    {
        foreach($array as $key => $value)
        {
            if (is_array($value))
            {  
                $array[$key] = multiArrayFlip($value);
            }
        }
    }
    else
    {
      $array = array_flip($array);
    }   

    return $array;
}

希望这会有所帮助:)