0

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
0

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.