在php中对数组进行分组并计算数据

时间:2017-06-10 04:20:37

标签: php arrays

最近我正在开展一个项目,对超级英雄'进行分类。和' Supervillains'基于他们的Franchaise'和超级大国的起源'。我想从数据库中获取数据,如数组#1,并在php中将它们显示为数组#2。

 Array #1

Array
(
  [0] => Array
    (
      [id] => 101
      [Name] => Superman
      [Franchise] => DC Comics
      [Superpower] => Inherent
    )

  [1] => Array
    (
      [id] => 908
      [Name] => Batman
      [Franchise] => DC Comics
      [Superpower] => Acquired
    )

  [2] => Array
    (
      [id] => 228
      [Name] => Wolverine
      [Franchise] => Marvel
      [Superpower] => Acquired
    )

  [3] => Array
    (
      [id] => 158
      [Name] => Iron Man
      [Franchise] => Marvel
      [Superpower] => Acquired
    )

  [4] => Array
    (
      [id] => 978
      [Name] => Thor
      [Franchise] => Marvel
      [Superpower] => Inherent
    )
)

阵列#1元素必须根据他们的特许经营权来分组。并计算其中有多少是“内在的”。或者'获得'就“超级大国”而言。

Array #2


Array
(
  [DC Comics] => Array
    (
      [Inherent] => 1
      [Acquired] => 1
    )

  [Marvel] => Array
    (
      [Inherent] => 1
      [Acquired] => 2
    )
)

3 个答案:

答案 0 :(得分:1)

  1. array_column()用于聚合2D数组的内部键。

  2. array_count_values()函数计算数组的所有值。

  3. 将此代码段用于计数值:

    $a = array ( array ("id" => "101", "Name" => "Superman", "Franchise" => "DC Comics", "Superpower" => "Inherent" ),
       array ( "id" => "908", "Name" => "Batman", "Franchise" => "DC Comics", "Superpower" => "Acquired" ),
       array ( "id" => "228", "Name" => "Wolverine", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
       array ( "id" => "158", "Name" => "Iron Man", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
       array ( "id" => "978", "Name" => "Thor", "Franchise" => "Marvel", "Superpower" => "Inherent" ));
      echo "<pre>";
    $return = array();
    // first group array values by franchise
    foreach($a as $val) {
        if (!isset($return[$val['Franchise']])) {
            $return[$val['Franchise']] = array();
        }
        $return[$val['Franchise']][] = $val;
    }
    $arr = array();
    // count elements by key value pair in particular franchise
    foreach ($return as $key => $value) {
        $tmp = array_count_values(array_column($value, 'Superpower'));
        $arr[$key] = $tmp;
    }
    print_r($arr);
    

    Demo is here

答案 1 :(得分:1)

单身和短array_reduce

// $arr is your initial array
$result = array_reduce($arr, function($r, $v){
    if (isset($r[$v["Franchise"]][$v["Superpower"]])) {
        $r[$v["Franchise"]][$v["Superpower"]] += $r[$v["Franchise"]][$v["Superpower"]];
    } else {
        $r[$v["Franchise"]][$v["Superpower"]] = 1;
    }
    return $r;
}, []);

print_r($result);

输出:

Array
(
    [DC Comics] => Array
        (
            [Inherent] => 1
            [Acquired] => 1
        )

    [Marvel] => Array
        (
            [Acquired] => 2
            [Inherent] => 1
        )
)

答案 2 :(得分:1)

这是没有太多逻辑的代码,

{
  "logos": [
    "05.png",
    "03.png",
    "01.png",
    "02.png",
    "04.png"
  ]
}