【问题标题】:Sum array integer values and Combine duplicated non integer values对数组整数值求和并合并重复的非整数值
【发布时间】:2018-07-22 03:21:44
【问题描述】:

我有一个如下所示的数组,我想将它们的非整数重复值作为与索引键关联的一个值,并在新索引中加上它们下一个索引中的整数值。一个不重复,只是将它们排序在同一个数组中。

我拥有的数据数组

Array
 (
 [0] => class 1
 [1] => 10
 [2] => class 1
 [3] => 10
 [4] => class 2
 [5] => 30
 [6] => late fine
 [7] => 50
 [8] => late fine
 [9] => 100
 )

我想要的方式

Array
 (
 [0] => class 1
 [1] => 20
 [2] => class 2
 [3] => 30
 [4] => late fine
 [5] => 150
 )

代码

$i=0; $x=0; $rec = array();

while($i < count($data)){       
    while($x < count($data)){           
        if($data[$i] == $data[$x]){         
            $rec[] = $data[$i];             
        }                   
        $x++;
    }

    $i++;
}       

【问题讨论】:

  • 我不懂 PHP,所以我将尝试解释我的想法。你可以从一个从i = 0开始并递增i=i+2的for循环开始,同时小于数组长度,然后是一个检查值的if语句,最后,当拉出数据时,你使用i+1索引。希望这是有道理的
  • I want to get their duplicated keys as one key in an index。没有重复的键,只有重复的值。我真的不明白你在问什么,看起来你的预期输出只是一个包含 20 而不是 10 的去重数组?
  • 对不起,我刚刚更新了问题

标签: php arrays sorting


【解决方案1】:

我不知道你为什么要以一个值数组结尾,其中每个其他值都应该代表前一个值的总和。

如果我是你,我会将它们排序为 KV 数组,如下所示:

$summed_array = [];
$array = [
    'class 1',
    40,
    'class 1',
    10,
    'class 2',
    20,
    'test 1',
    20,
    'test 1',
    40
]; // Your array

for( $i = 0; $i<count($array); $i++ ){

    // Do the following procedure for every other instance
    if( $i % 2 == 0 ){
        $summed_array[$array[$i]] = array_key_exists( $array[$i], $summed_array ) ? ( $summed_array[$array[$i]] + $array[$i+1] ) : $array[$i+1];
    }

}

这将为您提供如下输出:

Array ( [class 1] => 50 [class 2] => 20 [test 1] => 60 )

【讨论】:

  • 但我只需要索引顺序的结果
  • 在我的问题中喜欢上面的“我想要的方式”
【解决方案2】:

我同意Ole Haugset,但由于您坚持顺序结果,这里有一个解决方案:

$data = [
  'class 1',
  10,
  'class 1',
  10,
  'class 2',
  30,
  'late fine',
  50,
  'late fine',
  100
];

$temp = [];
foreach( array_chunk( $data, 2 ) as list( $key, $value ) ) {
  $temp[ $key ] = isset( $temp[ $key ] ) ? $temp[ $key ] + $value : $value;
}
// until here it was basically similar to Ole's solution

$result = [];
foreach( $temp as $key => $value ) {
  $result[] = $key;
  $result[] = $value;
}

var_dump( $result );

view parsed online @ eval.in

【讨论】:

  • 这两个答案都很好,我尊重两者,从道德上讲,我应该接受 Ole 的回答,因为他首先潜入水中,技术上还不错的回答,因为他提供的和我想要的一样,让我们​​投票给 Decent 吧: ) 大家开心
  • 很好地使用了array_chunk 作为@Decent Dabbler 的列表。我今天学到了一些新东西:)
猜你喜欢
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2017-01-28
  • 1970-01-01
  • 2011-08-30
  • 2011-10-29
相关资源
最近更新 更多