一系列排序算法

时间:2016-03-11 02:03:14

标签: php arrays algorithm sorting

我有一个多维数组,结构是这样的:

$arr1 = array(
0 => array(
    'name' => 'Jim',
    'awards' => array(
        0 => 'awards one',
        1 => 'awards two',
        2 => 'awards three',
        3 => 'awards four',
        4 => 'awards five',
        5 => 'awards six',
    ),
),
1 => array(
    'name' => 'Kate',
    'awards' => array(
        0 => 'awards one',
        1 => 'awards two',
        2 => 'awards three',
    ),
));

如果元素的“奖励”数量大于4,它将成为一个新元素,并在第五个元素之后包含“奖励”元素。像这样:

$arr2 = array(
0 => array(
    'name' => 'Jim',
    'awards' => array(
        0 => 'awards one',
        1 => 'awards two',
        2 => 'awards three',
        3 => 'awards four',
    ),
),
1 => array(
    'name' => 'Jim',
    'awards' => array(
        0 => 'awards five',
        1 => 'awards six',
    ),
),
2 => array(
    'name' => 'Kate',
    'awards' => array(
        0 => 'awards one',
        1 => 'awards two',
        2 => 'awards three',
    ),
));

我不擅长算法。我到处找,但找不到解决办法。有人能帮我吗。提前谢谢!

1 个答案:

答案 0 :(得分:1)

<?php
$arr1 = array(
    array(
        'name' => 'Jim',
        'awards' => array(
            0 => 'awards one',
            1 => 'awards two',
            2 => 'awards three',
            3 => 'awards four',
            4 => 'awards five',
            5 => 'awards six',
        ),
    ),
    array(
        'name' => 'Kate',
        'awards' => array(
            0 => 'awards one',
            1 => 'awards two',
            2 => 'awards three',
        ),
));

$result = array();
foreach( $arr1 as $player ) {
    while ( count($player['awards']) > 0 ) {
        $result[] = array(
            'name' => $player['name'],
            'awards' => array_splice($player['awards'], 0, 4)
        );
    }
}
var_export($result);

打印

array (
  0 => 
  array (
    'name' => 'Jim',
    'awards' => 
    array (
      0 => 'awards one',
      1 => 'awards two',
      2 => 'awards three',
      3 => 'awards four',
    ),
  ),
  1 => 
  array (
    'name' => 'Jim',
    'awards' => 
    array (
      0 => 'awards five',
      1 => 'awards six',
    ),
  ),
  2 => 
  array (
    'name' => 'Kate',
    'awards' => 
    array (
      0 => 'awards one',
      1 => 'awards two',
      2 => 'awards three',
    ),
  ),
)