문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

The reason that you can only address the items in object mode, is due to the way the json_decode was called.

To return $data as an associative array, use:

$newData=json_decode($data, true)
$newData=json_decode($data, true)

if you're passing the second param true then it converts the json to assosiative array(an array with key val pair).Official doc Here is official documentation Json_decode Php Official

an example to show that

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

its output will be

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top