PHP - 在assoc数组中排序数组

时间:2014-06-03 23:34:51

标签: php arrays sorting

我向您保证,我已经了解了许多关于PHP排序的SO Q,包括this mega one

我有一个PHP关联数组,字符串作为键。每个值都是一个整数数组。我想以简单的升序数字顺序对每个整数数组进行排序。我确信这应该很容易,而且我已经找到了足够多的例子,我认为我应该做正确的事情,但它不是很有效,所以有一个错字或我和#39;是个白痴还是什么......

PHP:

//Each fruit corresponds to an array (series) of integers
$data = [
    'banana' => [
        1,3,2
    ],
    'orange' => [
        5,1,3
    ]
];

echo "Before sort:\n";
var_dump($data);

//For each fruit, I want to order the numbers
foreach ($data as $key => $series)
{
    //Sort array of integers
    sort($series);

    //NB I wasn't sure about value/reference details of foreach loops, so I also tried
    //retrieving a series into a variable, sorting, and then reassigning back to the same key
}

echo "\n\nAfter sort:\n";
var_dump($data);

输出:

Before sort:
array(2) {
  'banana' =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(3)
    [2] =>
    int(2)
  }
  'orange' =>
  array(3) {
    [0] =>
    int(5)
    [1] =>
    int(1)
    [2] =>
    int(3)
  }
}


After sort:
array(2) {
  'banana' =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(3)
    [2] =>
    int(2)
  }
  'orange' =>
  array(3) {
    [0] =>
    int(5)
    [1] =>
    int(1)
    [2] =>
    int(3)
  }
}

如您所见,在输出中,内部整数数组尚未排序。我究竟做错了什么? (PHP 5.5.9,Windows 7)

1 个答案:

答案 0 :(得分:2)

使用引用&

foreach ($data as $key => &$series)
{
    //Sort array of integers
    sort($series);
    // OR
    // sort($data[$key]);
}