Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array:

Array
(
    ...
    [14] => Array
        (
            [date] => 2014-04-14
            [period] => 6
        )

    [15] => Array
        (
            [date] => 2014-04-21
            [period] => R1
        )

    [16] => Array
        (
            [date] => 2014-04-21
            [period] => R2
        )

    [17] => Array
        (
            [date] => 2014-04-21
            [period] => 4
        )

    [18] => Array
        (
            [date] => 2014-04-21
            [period] => 8
        )

    [19] => Array
        (
            [date] => 2014-04-28
            [period] => 1
        )
     ...
)

It has 2 types of sorts: Date and Period. But in the same time, the sort of the Period item is numeric and alphabetic. Looking the example of day 2014-04-21:

    [15] => Array
        (
            [date] => 2014-04-21
            [period] => R1
        )

    [16] => Array
        (
            [date] => 2014-04-21
            [period] => R2
        )

    [17] => Array
        (
            [date] => 2014-04-21
            [period] => 4
        )

    [18] => Array
        (
            [date] => 2014-04-21
            [period] => 8
        )

Is it possible to sort numerically and later alphabetically? I need a similar result:

[15] => Array
    (
        [date] => 2014-04-21
        [period] => 4
    )

[16] => Array
    (
        [date] => 2014-04-21
        [period] => 8
    )
[17] => Array
    (
        [date] => 2014-04-21
        [period] => R1
    )

[18] => Array
    (
        [date] => 2014-04-21
        [period] => R2
    )

I use this code:

function cmp($a, $b) {
    if ($a['date'] == $b['date']) { 
        if(is_numeric($a['period']) && !is_numeric($b['period'])) {
            return 1;
        }     
        else if(!is_numeric($a['period']) && is_numeric($b['period'])) {
            return -1;
        }
        else {
            return ($a['period'] < $b['period']) ? -1 : 1;
        }       
    }
    return (strtotime($a['date']) < strtotime($b['date']))? -1 : 1;
}

usort($arr, "cmp");
share|improve this question

1 Answer 1

up vote 1 down vote accepted

you should change direction in first two conditions:

if(is_numeric($a['period']) && !is_numeric($b['period'])) {
  return -1;
}     
else if(!is_numeric($a['period']) && is_numeric($b['period'])) {
  return 1;
}
share|improve this answer
    
I haven't seen this, thanks! –  csotelo Feb 19 '14 at 14:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.