Вопрос

$data = array(
    array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),
    array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '12/03/1980'),
    array('aa', 'name' => 'Paul', 'number' => 13, 'birthday' => '12/03/1980'),
    array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),
);

I want to sort the above array.

First,i want to sort the array by birthday.From that birthday i want to sort the array by number.I am excepting the output of the array like this,

$data = array(
        array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'), 
        array('aa', 'name' => 'Paul', 'number' => 13, 'birthday' => '12/03/1980'),
        array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '12/03/1980'),
        array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),        
    );

From various links i got this solution,which is not working as i excepted,it is sorting the value by number only

  usort($array, function($a, $b) { 
        $rdiff = $a->birthday - $b->birthday;
        if ($rdiff) return $rdiff; 
        return $a->number - $b->number; 
  });
Это было полезно?

Решение

The problem is birthday is a string. You need to convert it into an integer first using strtotime.

$rdiff = strtotime($a->birthday) - strtotime($b->birthday);

As those dates are in UK format you'll need to change the slashes between d/m/y to hyphens to, as when using slashes strtotime expects the date to be in US format, i.e. m/d/y. From the PHP manual:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

So use:

$rdiff = strtotime(str_replace('/', '-', $a->birthday)) - strtotime(str_replace('/', '-', $b->birthday));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top