PHP usort inside foreach order 按字母顺序排列

PHP usort inside foreach order alphabetically

我想弄清楚为什么我的代码不能像我预期的那样工作。我有一个数组:

$persons = array(
    0 => array(
        'person' => 'John',
        'children' => array('Eve', 'Mark', 'Alto')
    ),
    1 => array(
        'person' => 'Susy',
        'children' => array('Ruby', 'Adam', 'Tõnu')
    )
);

循环数组并按字母顺序对子项排序

foreach( $persons as $person ) {

    usort($person['children'], function( $a, $b ) {
        return strcmp( $a, $b );
    });
    var_dump($person['children']); //shows children array items alphabetically ordered

}

但是在 foreach chidrens 之后仍然处于启动顺序

var_dump($persons); //shows that children names are not ordered alphabetically

感谢您的宝贵时间

foreach 循环正在创建循环内数组值的有效副本。副本已排序但未更改原始数组。为此,您可以使用 &:

作为参考
foreach ($persons as &$person) {

来自documentation

On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one... In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

另一种直接引用数组的方法是遍历索引并引用元素:

for ($i = 0; $i < count($persons); $i++) {
    usort($persons[$i]['children']), function($a, $b) {
        return strcmp($a, $b);
    });
}