2014-03-30 58 views
2

如何獲取數組results中所有鍵位registration_id存在的位置?PHP獲取json數組鍵位

$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" 
          }] 
         }'; 

感謝您的幫助!

回答

1

您可以使用json_decode()

$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 
    } 
} 

或者,如果你想只保留其中registration_id存在的,使用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"); 
+1

我建議用戶'array_key_exists'代替isSet'的'因爲後者將返回'FALSE'如果密鑰存在但它的值爲'null' - http://it2.php.net/array_key_exists – Paolo

+0

感謝這個偉大的答案,但我需要獲得registration_id的完整結果數組中的位置,而不是此值鍵 –