PHP - 按2个值排序数组

时间:2015-12-28 10:12:32

标签: php multidimensional-array

考虑这个多维数组:

array(4) {
  [0]=>
  array(2) {
    ["number1"]=>
    int(100)
    ["number2"]=>
    int(24)
  }
  [1]=>
  array(2) {
    ["number1"]=>
    int(100)
    ["number2"]=>
    int(22)
  }
  [2]=>
  array(2) {
    ["number1"]=>
    int(300)
    ["number2"]=>
    int(30)
  }
  [3]=>
  array(2) {
    ["number1"]=>
    int(200)
    ["number2"]=>
    int(23)
  }
}

我需要将此数组按键' number1'进行升序排序。如果多个数组的number1值相同,则需要通过键“number2”按升序对数组进行排序。最终,这需要结果:

array(4) {
  [0]=>
  array(2) {
    ["number1"]=>
    int(100)
    ["number2"]=>
    int(22)
  }
  [1]=>
  array(2) {
    ["number1"]=>
    int(100)
    ["number2"]=>
    int(24)
  }
  [2]=>
  array(2) {
    ["number1"]=>
    int(200)
    ["number2"]=>
    int(23)
  }
  [3]=>
  array(2) {
    ["number1"]=>
    int(300)
    ["number2"]=>
    int(30)
  }
}

我已阅读有关array_multisort()函数的PHP手册,并阅读了一些关于此的stackoverflow帖子,但我无法做任何事情。

2 个答案:

答案 0 :(得分:1)

您可以使用array_multisort()执行此操作。你的代码应该是:

    $arr = array(
      array(
        "number1"=>100,
        "number2"=>24
      ),
      array(
        "number1"=>100,
        "number2"=>22
      ),
      array(
        "number1"=>300,
        "number2"=>30
      ),
      array(
        "number1"=>200,
        "number2"=>23
      ));
// Make a $tempArr for list of sort columns and their data to pass to array_multisort function  
    $tempArr = array();

    foreach($arr as $key=>$val) {
        $tempArr['number1'][$key] = $val['number1'];
        $tempArr['number2'][$key] = $val['number2'];
    }
// sort by number1 asc and then number2 asc
    array_multisort($tempArr['number1'], SORT_ASC, $tempArr['number2'], SORT_ASC,$arr);

    print_r($arr);

答案 1 :(得分:0)

如何通过usort

对其进行排序
$array = array( array('number' => 100, 'test' => 30),array('number' => 100, 'test' => 20),  array('number' => 40), array('number' => 60));
usort($array, "custom_sort");
// Define the custom sort function
function custom_sort($a,$b) {
  return $a['number'] > $b['number'];
}

输出

echo '<pre>';print_r($array );
Array
(
    [0] => Array
        (
            [number] => 40
        )

    [1] => Array
        (
            [number] => 60
        )

    [2] => Array
        (
            [number] => 100
            [test] => 20
        )

    [3] => Array
        (
            [number] => 100
            [test] => 30
        )

)