Search code examples
phparrayssortingcustom-sort

Sort array based only on trailing numbers in strings


I have an array that looks like this:

Array
(
    [0] => ripe@hobby.nl 20140827
    [1] => bas@hobby.nl 20130827
    [2] => bas@dikkenberg.net 20140825
    [3] => bas@hobby.nl 20120825
    [4] => ripe@hobby.nl 20140826
)

Now I want to sort this array in php based on the numbers only so ignoring the e-mail address in the sort process.


Solution

  • <?php
    $data = Array(0 => 'ripe@hobby.nl 20140827',
        1 => 'bas@hobby.nl 20130827',
        2 => 'bas@dikkenberg.net 20140825',
        3 => 'bas@hobby.nl 20120825',
        4 => 'ripe@hobby.nl 20140826'
    );
    
    $count_data = count($data);
    
    for($i=0;$i<$count_data;$i++)
    {
        $new_data[trim(strstr($data[$i], ' '))]=$data[$i];
    }
    echo "<pre>"; print_r($new_data);
    ?>
    

    this will return you

    Array
    (
        [20140827] => ripe@hobby.nl 20140827
        [20130827] => bas@hobby.nl 20130827
        [20140825] => bas@dikkenberg.net 20140825
        [20120825] => bas@hobby.nl 20120825
        [20140826] => ripe@hobby.nl 20140826
    )
    

    Now you can sort according to need by Key