Search code examples
phparraysarray-key

How to get the keys from array


I am using GCM(Google could messaging) for the very first time and i am stuck with some problem. Although the problem has nothing to do with the GCM.I have a JSON data

$data='{"multicast_id":7917175795873320166,"success":6,"failure":0,"canonical_ids":4,

"results":[

{"registration_id":"3","message_id":"m1"},
{"message_id":"m1"},
{"message_id":"m1"},
{"registration_id":"3","message_id":"m1"},

{"registration_id":"3","message_id":"m1"},

{"registration_id":"3","message_id":"m1"}]}';

$newData=json_decode($data);

Now what i want is the keys in the result array for which registration_id is set but i am unable to do so. I can access the registration_Id like $newData->results[0]->registration_id

I have found that array_keys() returns the keys in an array but how can i get the keys in the $newData->results array for which $newData->results[$index]->registration_id is set? The major issue is that i cant use the foreach loop for doing it. Hope i will get some help here.


Solution

  • Sure. First off, use the second param of json_decode so you're actually working with an array and not an object. Then filter the array with the items you want (where registration_id is set) and get the keys.

    $newData=json_decode($data, true);
    
    $filteredResults = array_filter($newData['results'], function($item) {
        return isset($item['registration_id']);
    });
    
    print_r(array_keys($filteredResults));
    

    Working example: http://3v4l.org/e8doL

    Note this code assumes you are using PHP 5.3 or later. If you are on an earlier version, you'll need to define your array_filter callback function first and pass it in rather than using an anonymous function.