Need to get all the age keys and count the number of them greater than 50. Given data
$data = '{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}';
Output should be 2 as there are 2 ages greater than 50
This is what I am trying
$array = json_decode($data, true);
$strArray = explode(',', $array['data']);
$temp1 = array();
for($i=0; $i < count($strArray); $i++){
$key_value = explode('=', $strArray[$i]);
$temp1[$i][$key_value[0]] = $key_value[1];
}
print "<pre>";
print_r($temp1);
print "</pre>";
Output is coming as
Array
(
[0] => Array
(
[key] => IAfpK
)
[1] => Array
(
[ age] => 58
)
[2] => Array
(
[ key] => WNVdi
)
[3] => Array
(
[ age] => 64
)
[4] => Array
(
[ key] => jp9zt
)
[5] => Array
(
[ age] => 47
)
)
Need to get all the ages in an array to compare.
4
Answers
An effective way to achieve this since your data is strangely formatted would be to use regex. For some reason, the
?:
non capturing group is still being captured so all of the ages will be in the second capture group of the match array – you can play to optimise that.Once you have all your ages in an array, a simple
array_filter
for ages larger than 50 is more than enough. You can see a live working example on 3v4l.org.Ofc, if you then need the corresponding key, you will need to do more magic.
If you’re using less than PHP 7.4, arrow functions are not supported. You can instead replace
$greaterThan50
assignment to:See it working live on 34vl.org
If your data is truly semi-structured like that and isn’t too massive, and you want to keep the keys, I think this is a good case for
array_shift
to reduce the array until it is exhausted:Demo: https://3v4l.org/RIF2q
You should hopefully be able to add whatever logic you need to test ages then.
Based on your logic, You can do it as follows :
Short and simple. Hope this will work for you,