rinchik
rinchik

Reputation: 2670

PHP Flipping multidimentional array doesn't work

I come up with this code:

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

but it doesnt work. It returns unchanged array.

here is the array data sample:

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

Upvotes: 0

Views: 438

Answers (2)

Sabari
Sabari

Reputation: 6335

You need to modify your function to work it correctly. Reassign the values after 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;
}

Hope this helps :)

Upvotes: 1

Smorko
Smorko

Reputation: 253

You have to reassign the return value of the array_flip function to your $array variable in order to work.

Upvotes: 1

Related Questions