Return to Snippet

Revision: 22835
at January 23, 2010 20:36 by AlejoLuc


Initial Code
/**
 * sort_array_by_key()
 * 
 * @param array $array
 * @param string|int $key
 * @return array
 * 
 * @author Alejo
 */
function array_sort_by_key($array, $key)
{
    $tmpArKeys = array();
    foreach ($array as $ar_item)
    {
        $tmpArKeys[] = $ar_item[$key];
    }
    asort($tmpArKeys);

    $newAr = array();
    foreach ($tmpArKeys as $n_key => $n_val)
    {
        $newAr[] = $array[$n_key];
    }
    return $newAr;
}


/// Example

$people = array(
                array(
                'Name' => 'John',
                'Lastname' => 'Doe',
                'E-mail' => '[email protected]'
                ),
                array(
                'Name' => 'Harry',
                'Lastname' => 'Potter',
                'E-mail' => '[email protected]'
                ),
                array(
                'Name' => 'Lady',
                'Lastname' => 'Gaga',
                'E-mail' => '[email protected]'
                )

                );

$sorted_people = array_sort_by_key($people, 'Name');
print_r($sorted_people);

/// Example output:
/*
Array
(
    [0] => Array
        (
            [Name] => Harry
            [Lastname] => Potter
            [E-mail] => [email protected]
        )

    [1] => Array
        (
            [Name] => John
            [Lastname] => Doe
            [E-mail] => [email protected]
        )

    [2] => Array
        (
            [Name] => Lady
            [Lastname] => Gaga
            [E-mail] => [email protected]
        )

)

*/

Initial URL

                                

Initial Description
Simple function that sorts a bi-dimensional array by one of it keys.

Initial Title
Sort bidimensional array by one of it keys

Initial Tags
php, sort, array

Initial Language
PHP