我有一组数字(邮政编码区域),例如:
Array (
[0] => 34
[1] => 35
[2] => 36
[3] => 51
[4] => 53
[5] => 54
[6] => 55
[7] => 56
[8] => 57
[9] => 60
[10] => 61
[11] => 63
[12] => 64
[13] => 65
[14] => 66
[15] => 67
[16] => 68
[17] => 69
[18] => 74
[19] => 97
)
我想将数组中的数字相加:
Array (
[0] => 34-36
[1] => 51
[2] => 53-57
[3] => 60-61
[4] => 63-69
[5] => 74
[6] => 97
)
我如何通过PHP实现这一目标?
答案 0 :(得分:0)
这是获得所需输出的逻辑。
$arr = array (34,35,36,51,53,54,55,56,57,60,61,63,64,65,66,67,68,69,74,97);
$sum_arr = array();
$prev_val = 0;
foreach($arr as $key => $val)
{
/* Store initial value in array */
if($key == 0)
{
$sum_arr[] = $val;
}
/* If value is not sequence */
else if(($prev_val+1) != $val)
{
/* Get last index of array and append current value */
$sum_last_idx = count($sum_arr) - 1;
/* Append value only if both values are not equal */
if($sum_arr[$sum_last_idx] != $prev_val)
{
$sum_arr[$sum_last_idx] = $sum_arr[$sum_last_idx] . '-' . $prev_val;
}
$sum_arr[] = $val;
}
/* Retain previous value */
$prev_val = $val;
}
print_r($sum_arr);
输出
Array
(
[0] => 34-36
[1] => 51
[2] => 53-57
[3] => 60-61
[4] => 63-69
[5] => 74
[6] => 97
)
答案 1 :(得分:0)
逻辑上,在php的帮助下你可以获得所需的输出
$zipArr = array ("0" => 34,"1" => 35,"2" => 36,"3" => 51,"4" => 53,"5" => 54,"6" => 55,"7" => 56,"8" => 57,"9" => 60,"10" => 61,"11" => 63,"12" => 64,"13" => 65,"14" => 66,"15" => 67,"16" => 68,"17" => 69,"18" => 74,"19" => 97,);
$range = range(10,100,10);
print_r($zipArr);
$new_arr = [];
foreach($range as $rValue){
$tmpArr = [];
foreach($zipArr as $zipValue){
if($zipValue%$rValue < 10){
$tmpArr[] = $zipValue;
}
}
if(!empty($tmpArr)){
if(count($tmpArr) > 1){
$new_arr[] =($tmpArr[0] ." - ".end($tmpArr));
} else {
$new_arr[] =($tmpArr[0]);
}
}
}
$new_arr = array_unique($new_arr);
print_r($new_arr);
输出
Array
(
[0] => 34 - 36
[1] => 60 - 69
[3] => 51 - 57
[5] => 74
[6] => 97
)