douhao3562 2014-01-13 13:22
浏览 21
已采纳

如何从数组中获取密钥

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.

  • 写回答

3条回答 默认 最新

  • dp0518 2014-01-13 13:27
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?