0

I have a json like this:

{
"data": [
{
"prop1":"aaa",
"prop2":"bbb",
"prop3":"1234",
"prop4":"2006"
},
{
"prop1":"ccc",
"prop2":"ddd",
"prop3":"4567",
"prop4":"2016"
},
{
"prop1":"aaa",
"prop2":"ddd",
"prop3":"4567",
"prop4":"2002"
}
]}

It will have ~100 elements and I need to count elements with specified property, I tried something with

echo count($json['data']);

but it will get me count of all elements of json - I need to know the number of elements with prop1 => "aaa"

what I have so far:

$file = "test.json";

$fh = fopen($file, 'a') or die();
$json = json_decode(file_get_contents($file), true);



echo '<pre>';
print_r($json);
exit();

?>

1 Answer 1

1

Use array_filter to create a callback filter function

<?php 


$json = '{
"data": [
{
"prop1":"aaa",
"prop2":"bbb",
"prop3":"1234",
"prop4":"2006"
},
{
"prop1":"ccc",
"prop2":"ddd",
"prop3":"4567",
"prop4":"2016"
},
{
"prop1":"aaa",
"prop2":"ddd",
"prop3":"4567",
"prop4":"2002"
}
]}';



echo '<pre>';
$data = json_decode($json);
print_r($data->data);
$data->data = array_filter($data->data, function($item) { 
    return $item->prop1 == 'aaa';
});
print_r($data->data);
exit();

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.