自然地排序2D PHP数组

时间:2015-04-09 09:25:03

标签: php arrays sorting multidimensional-array

好的,我正式疯狂。我尝试过在网上找到的所有解决方案,但没有一个能正常工作。

我有这个数组:

$hits = array(
    array('sortby' => 'String 1', 'html' => '<div>This element contains String 1</div>',
    array('sortby' => 'String 11', 'html' => '<div>This element contains String 11</div>',
    array('sortby' => 'String 2', 'html' => '<div>This element contains String 2</div>',
);

我想通过“sortby”键自然地对$ hits数组进行排序,因此输出结果如下:

 <div>This element contains String 1</div>
 <div>This element contains String 2</div>
 <div>This element contains String 11</div>

我可以使用哪种排序功能?

3 个答案:

答案 0 :(得分:3)

只需使用usort()进行strnatcmp()比较。

$hits = array(
    array('sortby' => 'String 1', 'html' => '<div>This element contains String 1</div>'),
    array('sortby' => 'String 11', 'html' => '<div>This element contains String 11</div>'),
    array('sortby' => 'String 2', 'html' => '<div>This element contains String 2</div>')
);

usort($hits, function($a, $b) {
    return strnatcmp($a['sortby'], $b['sortby']);
});

var_dump($hits);

/*
array(3) {
  [0]=>
  array(2) {
    ["sortby"]=>
    string(8) "String 1"
    ["html"]=>
    string(41) "<div>This element contains String 1</div>"
  }
  [1]=>
  array(2) {
    ["sortby"]=>
    string(8) "String 2"
    ["html"]=>
    string(41) "<div>This element contains String 2</div>"
  }
  [2]=>
  array(2) {
    ["sortby"]=>
    string(9) "String 11"
    ["html"]=>
    string(42) "<div>This element contains String 11</div>"
  }
}
*/

答案 1 :(得分:1)

usort($hits, function($a, $b){
    return strnatcmp($a['sortby'], $b['sortby']);
});

答案 2 :(得分:0)

尝试以下:

<?php
$hits = array(
    array('sortby' => 'String 1', 'html' => '<div>This element contains String 1</div>'),
    array('sortby' => 'String 11', 'html' => '<div>This element contains String 11</div>'),
    array('sortby' => 'String 2', 'html' => '<div>This element contains String 2</div>')
);

function comp($a, $b) {
    $n1 = intval(substr($a['sortby'], 7));
    $n2 = intval(substr($b['sortby'], 7));
    return $n1>$n2;
}

usort($hits, "comp");

print_r($hits);

?>

使用usort(),您可以应用排序规则。