My json is this :
{
"id1527":{"stats":"true"},
"id6376373":{"stats":"true"},
"id63737":{"stats":"true"}
}
how can get count of all ids(like 'id1527' or 'id6376373'...)
Decode to an array and count the elements.
count(json_decode($json, true));
I hope you mean this.
$str = '{"id1527":{"stats":"true"},"id6376373":{"stats":"true"},"id63737":"stats":"true"},"x444":{"stats":"false"}}';
echo count(preg_grep("/^id(\d)+$/",array_keys(json_decode($str,true))));
This code snippet checks to see whether the top-level key of the JSON array has a preceding text "id" and take only those records into account.
After parsing the JSON, array_filter()
to filter this just to the ones with a key that begins with id
, and count()
to count them:
count(array_filter(json_decode($json, true), function($key) {
return substr($key, 0, 2) == "id";
}, ARRAY_FILTER_USE_KEY));