【问题标题】:Count a specific value from PHP array从 PHP 数组中计算特定值
【发布时间】:2022-01-12 01:11:19
【问题描述】:

我管理此代码以获取数组中特定值的计数 它工作正常,但有没有更好的方法来简化它?

$array= '[
{"s":1},
{"s":1},
{"s":2},
{"s":5}
]';

$json=json_decode($array);
 $count1=0;
 $count2=0;
$count5=0;
        foreach( $json as $j ) { 
          if($j->s===1){
            $count1++;
          };
  if($j->s===2){
            $count2++;
          };
  if($j->s===5){
            $count5++;
          };

        }
        echo $count1; // 2
echo $count2; // 1
echo $count5; // 1

【问题讨论】:

  • array_count_values(array_column(json_decode($json), 's'));
  • 谢谢,请添加为答案

标签: php arrays


【解决方案1】:

您可以将代码简化为以下内联解决方案:

$result = array_count_values(array_column(json_decode($json), 's'));

# $json is a JSON string
# json_decode transforms a string into an array of objects
# array_column takes all "s" properties from all objects and returns an array
# array_count_values counts occurrences of array elements and returns an array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-06
    • 2020-10-19
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多