对数组或数组进行排序?

时间:2017-01-22 18:30:57

标签: php arrays sorting

我希望下面的数组排序。如果名称来自倍数,我想添加总数。我也希望重新排列这个数字。它可以是索引+ 1.

array (
  0 => array ('name' => 'Dave', 'number' => '1', 'total' => 1),
  1 => array ('name' => 'Tom', 'number' => '2', 'total' => 1),
  2 => array ('name' => 'Dave', 'number' => '3', 'total' => 2),
  3 => array ('name' => 'Amy', 'number' => '4', 'total' => 1),
);

array (
  0 => array ('name' => 'Dave', 'number' => '1', 'total' => 3),
  1 => array ('name' => 'Tom', 'number' => '2', 'total' => 1),      
  2 => array ('name' => 'Amy', 'number' => '3', 'total' => 1),
);

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用自定义$group数组和array_values函数的解决方案:

$arr = array (
 array ('name' => 'Dave', 'number' => '1', 'total' => 1),
 array ('name' => 'Tom', 'number' => '2', 'total' => 1),
 array ('name' => 'Dave', 'number' => '3', 'total' => 2),
 array ('name' => 'Amy', 'number' => '4', 'total' => 1),
);

$group = [];
foreach ($arr as $item) {
    if (isset($group[$item['name']])){
        $group[$item['name']]['total'] += $item['total'];
    } else {
        $group[$item['name']] = $item;
    }
}
$result = array_values($group);

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [name] => Dave
            [number] => 1
            [total] => 3
        )

    [1] => Array
        (
            [name] => Tom
            [number] => 2
            [total] => 1
        )

    [2] => Array
        (
            [name] => Amy
            [number] => 4
            [total] => 1
        )
)

更新: 如果number键应反映每个项目的序列位置,请使用以下方法使用自定义$count变量:< / p>

...
$group = [];
$count = 1;
foreach ($arr as $item) {
    if (isset($group[$item['name']])){
        $group[$item['name']]['total'] += $item['total'];
    } else {
        $item['number'] = $count++;
        $group[$item['name']] = $item;
    }
}
...