skip to Main Content

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


  1. 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.

    $data = '{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}';
    
    preg_match_all('/(?:age=)([0-9]+)/', json_decode($data)->data, $matches, PREG_PATTERN_ORDER);
    
    // Only continue if we found any ages in the string
    if (array_key_exists(1, $matches))
    {
        // 58, 64
        $greaterThan50 = array_filter($matches[1], fn($age) => intval($age) > 50);
    }
    

    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:

    $greaterThan50 = array_filter($matches[1], function($age) {
        return intval($age) > 50;
    });
    

    See it working live on 34vl.org

    Login or Signup to reply.
  2. 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:

    $data = '{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}';
    $array = json_decode($data, true);    
    $strArray = explode(',', $array['data']);
    
    $clean = [];
    while(count($strArray) >= 2){
        $key = explode('=', array_shift($strArray))[1];
        $age = explode('=', array_shift($strArray))[1];
        $clean[$key] = (int)$age;
    }
    
    var_dump($clean);
    

    Demo: https://3v4l.org/RIF2q

    You should hopefully be able to add whatever logic you need to test ages then.

    Login or Signup to reply.
  3. Based on your logic, You can do it as follows :

    <?php
    
    $data = '{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}';
    
    $array = json_decode($data, true);    
    $strArray = explode(',', $array['data']);
    $keys = array();
    $ages = array();
    for($i=0; $i < count($strArray); $i++){
        $key_value = explode('=', $strArray[$i]);
        if ((int)$key_value[1] > 0 ) {
            array_push($ages, $key_value[1]);
        } else {
            array_push($keys, $key_value[1]);
        }
    }
    
    $result = array_combine($keys, $ages);
    $result = array_filter($result, function($age) {
        return intval($age) > 50;
    });
    print "<pre>";
    print_r($result);
    print "</pre>";
    
    Login or Signup to reply.
  4. Short and simple. Hope this will work for you,

    $output = [];
    $data = '{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}';
    $array = json_decode($data, true);
    foreach (explode(',',$array['data']) as $key => $value)
    {
        if(str_contains($value,'age'))
        {
            $age = explode('=',$value);
            if($age[1] > 50)
            {
                array_push($output, $age[1]);
            }
        }
    }
    print_r($output);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search