gpt4 book ai didi

php - 对 PHP 数组编号进行分组

转载 作者:可可西里 更新时间:2023-10-31 23:42:35 25 4
gpt4 key购买 nike

我该如何改变:

Array(    [0] => 1    [1] => 2    [2] => 3    [3] => 4    [4] => 5    [5] => 6    [6] => 7    [7] => 11    [8] => 21    [9] => 22    [10] => 23    [11] => 24)

对此:

1-7, 11, 21-24

我在 PHP 数组中有一个这样的数字列表,我只是想让这个列表小一点。

2000: 3 6 7 11 15 17 25 36 42 43 452001: 2 3 4 5 6 9 10 11 12 13 34 37 45 46 47 48 49 50 51 522002: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 33 34 35 36 37 39 40 41 42 43 44 45 46 47 48 49 50 51 522003: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 512004: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 21 22 23 24 25 26 27 28 29 30 31 32 33 34 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 522005: 1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 522006: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 522007: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

最佳答案

有趣的任务。

这是一个演示脚本,可以完全满足您的需求。

调整口味。

代码

<?php

$groups = array();
$active_group = 0;

$output = array();
$output_counter = 0;

$nums = array( 1, 2, 3, 4, 5, 6, 7, 11, 21, 22, 23, 24 );


foreach( $nums as $k => $num ) {

// if this isn't the first item, and the current number
// isn't one more than the previous one, increment the counter
if( $k !== 0 && $nums[$k] !== $nums[$k-1]+1 )
$active_group ++;

// add this number to a group
$groups[ $active_group ][] = $num;

}


// take the 1st and last of each group
foreach( $groups as $group ) {

$first = array_shift( array_values($group) );
$output[$output_counter][] = $first;

$last = array_pop( array_values($group) );
if( $first !== $last )
$output[$output_counter][] = $last;

$output_counter++;

}


echo '<pre>';
print_r($output);

?>

输出

Array
(
[0] => Array
(
[0] => 1
[1] => 7
)

[1] => Array
(
[0] => 11
)

[2] => Array
(
[0] => 21
[1] => 24
)

)

关于php - 对 PHP 数组编号进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11875006/

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