2

How can I get all the positions in the array resultswhere the key registration_id exists ?

  $json_raw = '{"multicast_id":6446899316497614986,
                     "success":5,
                     "failure":1,
                     "canonical_ids":3,
                     "results":[
                             {"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
                               "message_id":"0:1396175384218906%50b5570df9fd7ecd"
                             },
                             {"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
                              "message_id":"0:1396175384218155%50b5570df9fd7ecd"
                             },
                             {"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
                              "message_id":"0:1396175384219100%50b5570df9fd7ecd"
                             },
                             {"message_id":"0:1396175384218718%b91f4d1ff9fd7ecd"
                             },
                             {"message_id":"0:1396175384219927%50b5570df9fd7ecd"
                             },
                             {"error":"InvalidRegistration"
                             }]
                       }';

Thanks for any help!

1 Answer 1

1

You can use json_decode() for this.

$data = json_decode($json_raw, TRUE);
foreach ($data['results'] as $key=>$result) {
    if (array_key_exists('registration_id', $result)) {
       //use now via $data['results'][$key] or simply $result
    }
}

Or if you want to only keep the ones where registration_id exists, use array_filter():

function registrationIdExists($result) {
    return array_key_exists('registration_id', $result);
}

$data = json_decode($json_raw, TRUE);
$data['results'] = array_filter($data['results'], "registrationIdExists");
Sign up to request clarification or add additional context in comments.

2 Comments

I'd suggest user array_key_exists instead of isSet as the latter would return false if the key exists but its value is null - it2.php.net/array_key_exists
Thanks for this great answer, but i need to get the position in the complete results array of registration_id and not the value of this key

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.