繁体   English   中英

如何从数组 PHP 中计算特定值?

[英]How to count specific value from array PHP?

我有一个多维数组,我需要计算它们的具体值

Array
(
 [0] => Array
    (
      [Report] => Array
        (
         [id] => 10
         [channel] => 1
         )
     )

    [1] => Array
      (
       [Report] => Array
         (
           [id] => 92
           [channel] => 0
         )
      )

    [2] => Array
      (
         [Report] => Array
         (
            [id] => 18
            [channel] => 0
         )
      )
    [n] => Array
)

我需要得到这样的输出:channel_1 = 1; channel_0 = 2 等

我用 foreach 做了一个函数:

foreach ($array as $item) {
  echo $item['Report']['channel'];
} 

我得到:1 0 0 ...但我怎么能像这样计算它:channel_1 = 1; channel_0 = 2,channel_n = n 等等?

尝试这个。 有关分步说明,请参阅注释。 输出:

array(2) {
  ["channel_1"]=>
  int(1)
  ["channel_0"]=>
  int(2)
}

代码:

<?php

// Your input array.
$a =
[
    [
        'Report' =>
        [
            'id' => 10,
            'channel' => 1
        ]
    ],
    [
        'Report' =>
        [
            'id' => 92,
            'channel' => 0
        ]
    ],
    
    [
        'Report' =>
        [
            'id' => 18,
            'channel' => 0
        ]
    ]
];

// Output array will hold channel_N => count pairs
$result = [];

// Loop over all reports
foreach ($a as $report => $values)
{
    // Key takes form of channel_ + channel number
    $key = "channel_{$values['Report']['channel']}";
    
    if (!isset($result[$key]))
        // New? Count 1 item to start.
        $result[$key] = 1;
    else
        // Already seen this, add one to counter.
        $result[$key]++;
}

var_dump($result);
/*
Output:
array(2) {
  ["channel_1"]=>
  int(1)
  ["channel_0"]=>
  int(2)
}
*/

您可以使用array_column()array_count_values()没有循环的情况下轻松完成此操作。

$reports = array_column($array, 'Report');
$channels = array_column($reports, 'channel');
$counts = array_count_values($channels);

$counts现在将等于一个数组,其中键是通道,值是计数。

Array
(
    [1] => 1
    [0] => 2
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM