gpt4 book ai didi

php - 数组排序算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:19:24 24 4
gpt4 key购买 nike

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

$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',
),
));

如果其中一个元素的'awards'数大于4,它将成为一个新元素,并在第五个之后包含'awards'元素。像这样:

$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',
),
));

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

最佳答案

<?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',
),
),
)

关于php - 数组排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com