简化数组PHP中的数组重复元素

时间:2019-02-20 09:49:18

标签: php arrays multidimensional-array

我们如何找到multidimensional array中重复元素的数量,

我有一个像这样的数组:

Array 
      ( 
          [0] => Array 
              ( 
                  [brti] => 29 
              ) 
          [1] => Array 
              ( 
                  [voda] => 6 
              ) 
          [2] => Array 
              ( 
                  [btel] => 8 
              ) 
          [3] => Array 
              ( 
                  [btel] => 10 
              ) 
      )

问题:如何简化数组的结构,我的意思是如果有指示具有相同的键,则可以对值进行计数?

就是这样:

Array 
  ( 
      [0] => Array 
          ( 
              [brti] => 29 
          ) 
      [1] => Array 
          ( 
              [voda] => 6 
          ) 
      [2] => Array 
          ( 
              [btel] => 18 
          ) 
  )

到目前为止,我已经尝试过这种方法,但是对我没有帮助My array is store in $test

    $test = [sample array]

    $count = array();
    foreach ($test as $key => $value) {
        foreach ($value as $k => $val) {
            if (isset($count[$val])) {
                ++$count[$val];
            } else {
                $count[$value] = 1;
            }
        }
    }
    print_r($count);

2 个答案:

答案 0 :(得分:1)

<?php

$array = [
    "0" => ["brti" => 29],
    "1" => ["voda" => 6],
    "2" => ["btel" => 8],
    "3" => ["btel" => 10],
];
$final = array();

array_walk_recursive($array, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});
print_r($final);

    });

check demo

答案 1 :(得分:0)

您可以通过非常简单的方式来完成

$test = [];
foreach ($array as $value)
{
    foreach ($value as $k => $v)
    {
        // $test[$k] = ($test[$k] ?? 0); // initialised if not php 7+
        $test[$k] = (empty($test[$k]) ? 0: $test[$k]); //  below php 7 
        $test[$k] += $v;
    }
}

print_r($test);

输出:

Array
(
    [brti] => 29
    [voda] => 6
    [btel] => 18
)

工作demo