phparrayssortingmultidimensional-arrayalternating

Sort a 2d array to achieve alternating values in a column


So I have this array.

Array
(
    [0] => Array
        (
            [key_1] => something
            [type] => first_type
        )

    [1] => Array
        (
           [key_1] => something_else
           [type] => first_type
        )

    [2] => Array
        (
            [key_1] => something_else_3
            [type] => second_type
        )

    [3] => Array
        (
            [key_1] => something_else_4
            [type] => second_type
        )
)

I have to sort by type value in a pattern like this:

first_type
second_type
first_type
second_type

How can I do this?


Solution

  • So here's how I got it to work:

    function filter_by_value($array, $index, $value) { 
        if(is_array($array) && count($array) > 0)  { 
            foreach(array_keys($array) as $key){ 
                $temp[$key] = $array[$key][$index]; 
                if ($temp[$key] == $value){ 
                    $newarray[$key] = $array[$key]; 
                } 
            } 
        } 
        return $newarray;
    }
    $array = /* array here */ 
    $type1 = array_values(filter_by_value($array, 'type', '1'));
    $type2 = array_values(filter_by_value($array, 'type', '2'));
    $i = 1; $x = 1; $y = 1;
    $sorted = array();
    foreach ($array as $a) {
        if ($i % 2) {
            $sorted[$i-1] = $type1[$x-1];
            $x++;
        } else {
            $sorted[$i-1] = $type2[$y-1];
            $y++;
        }
        $i++;
    }
    

    Found filter_by_value() on php.net but I don't remember where so, that's not made by me. Maybe this is not the best solution but it works pretty fine.