Home > Blockchain >  Count a specific value from PHP array
Count a specific value from PHP array

Time:01-12

I managed this code to get the count of specific value inside the array It works fine, but Is there a better way to simplify it?

$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

CodePudding user response:

You can simplify your code to the following inline solution:

$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
  •  Tags:  
  • Related