合并多维数组中的键

时间:2019-11-26 06:22:07

标签: php arrays multidimensional-array

我有这个多维数组:

array(3) {
     [0]=>
        array(2) {
          ["casestatus"]=> string(4) "Open"
          ["casestatus_count"]=> int(2)
        }
     [1]=>
       array(2) {
          ["casestatus"]=> string(7) "Pending"
          ["casestatus_count"]=> int(1)
        }
     [2]=>
       array(2) {
          ["casestatus"]=> string(4) "Open"
          ["casestatus_count"]=> int(1)
        }
    }

从上面的数组中,我可以基于casestatus键进行合并,如下所示:

    $newArray = array();

    foreach($mergedData as $data)
    {
        if(!isset($newArray[$data["casestatus"]]))
        {
            $newArray[$data["casestatus"]] = array(
                "casestatus" => $data["casestatus"],
                "casestatus_count" => 0
            );
        }

        $newArray[$data["casestatus"]]["casestatus_count"] += $data["casestatus_count"];
    }

    var_dump($newArray);

我从中得到:

array(2) {
    ["Open"]=>
       array(2) {
         ["casestatus"]=> string(4) "Open"
         ["casestatus_count"]=> int(3)
       }
    ["Pending"]=>
       array(2) {
         ["casestatus"]=> string(7) "Pending"
         ["casestatus_count"]=> int(1)
       }
  }

请注意,我的阵列键是我的casestatus。所以有没有这种方法,而是将我的数组键设置为:

array(2) {
    [0]=>
       array(2) {
         ["casestatus"]=> string(4) "Open"
         ["casestatus_count"]=> int(3)
       }
    [1]=>
       array(2) {
         ["casestatus"]=> string(7) "Pending"
         ["casestatus_count"]=> int(1)
       }
  }

2 个答案:

答案 0 :(得分:2)

在此过程之后只需array_values($newArray)

var_dump(array_values($newArray));

array_values()

答案 1 :(得分:0)

您可以创建状态图以计数,然后对其求和:

<?php
$tickets =
[
    [
        'status' => 'Open',
        'count'  => 2
    ],
    [
        'status' => 'Closed',
        'count'  => 1
    ],
    [
        'status' => 'Open',
        'count'  => 1
    ]
];
foreach($tickets as $ticket)
    $status_counts[$ticket['status']][] = $ticket['count'];

foreach($status_counts as $status => $counts)
    $result[] = [
        'status' => $status, 
        'count' => array_sum($counts)
    ];

var_export($result);

输出:

array (
    0 => 
    array (
      'status' => 'Open',
      'count' => 3,
    ),
    1 => 
    array (
      'status' => 'Closed',
      'count' => 1,
    ),
  )

但是更简单的格式可能就足够了:

$result = array_map('array_sum', $status_counts);
var_export($result);

输出:

array (
    'Open' => 3,
    'Closed' => 1,
  )