从 PHP 数组中计算特定值[重复]

问题描述 投票:0回答:1

我管理此代码来获取数组内特定值的计数 它工作得很好,但是有更好的方法来简化它吗?

$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
php arrays
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.