0

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");

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.