phparrayssortingmultidimensional-arraygrouping

Sort database result set by earliest position of a column value


I have an array pulled back from a database that is ordered by number ([0]=>'',[1]=>''...etc) within each element there are various associative values (title,date,area...etc). I need the array reordering so that all the elements with the same 'area' variable appear together. So effectively we will still have a ([0]=>'',[1]=>''...etc) array but the first 5 or so will have the same 'area' then the next however many will have the same 'area' and so on.

To make it easier there are 4 possible values for the 'area' field (north,west,central,blyth valley).

What I don't want is a multi-dimensional array grouped by the 4 areas, I need it as one long array just in the order that puts all 'like' areas together.


Solution

  • Here is a solution...

    $arr = array(
        '0' => array( 'area' => 'west' ),
        '2' => array( 'area' => 'north' ),
        '3' => array( 'area' => 'west' ),
        '4' => array( 'area' => 'central' ),
        '5' => array( 'area' => 'west' ),
        '6' => array( 'area' => 'north' )
    );
    
    $new = array();
    
    // Get a list of possible areas
    $areas = array();
    foreach ($arr as $key => $value) {
        if ( ! in_array( $value['area'] , $areas ) ) {
            array_push( $areas, $value['area'] );
        }
    }
    
    // For each area...
    foreach ($areas as $key => $area) {
        // Find a area that matches...
        foreach ($arr as $key => $value) {
            if ( $value['area'] == $area ) {
                array_push( $new, $value );
            }
        }
    }
    

    Also you may want to remove the first loop if there are only a set number of areas. Just fill the areas array with a list of possible areas in the order you want.