0

I'm trying to get data from an associated array inside an associated array. The data is like this:

{
  "keys": [
    {
      "kid": "28f5813e327ad14caaf1bf2a12368587e882b604",
      "e": "AQAB",
      "kty": "RSA",
      "alg": "RS256",
      "n": "y-Ssr1zlqWaldUHklobfrJLZkkBYrLVKTOk9SnzkG3v2LPB-0lxLQjm8UDpdZRErn4_FfCQ6b7SAObUp2XgcD-fwmYfq34mvY-xGcvlEarcOFdVD9cwkGBdXL_VJYzqLtvuAL30mbD2TGhIp-QCV-rqb6ujh75vSmwWH1Kkx1HNkVbXHHETvX7h8kj3zmCtRdMGeQJ2YrcJHz3GnJx0M2Zpq1HiAXkYL9GUYsq9maONfsrSeACu7T0W4v-XTppsV3DwU89D_eFd8gJsONvFZPvbqyGivdXYTnYNo7Jf01IisO4JZZrNgUlVT-gPkTM1O1UXevgFY62Br8mBot6Lw6Q",
      "use": "sig"
    },
    {
      "alg": "RS256",
      "n": "timkjBhJ0F7fgr5-ySitSoSNmUqYcVKgWaUd52HUYPowNwdw1vOWYHuSVol47ssOOaF7dRjgoVHyo_qNgy7rdlU0pUidiYTB6lwSAQYyvk6WAipkpzWH8cr875BMUREyN5aEy-iKsYTB3HeT-gEnLI697eETZtSB8rwlDvyRy7l0wD1GVj4SKTd4P2a2qNCgCfkZzzKqPgmIrPtwkEZb43Cz-A7AfwyXxrMljTkghKkp4zkFRtXplIGjC5LcPZRLSseTYwHP2pV4AtE5KzYxDmtDmY6RyZaMZc_WXNvKBFcO3Rypo4F63lE2x5f7EIbpATWydXq3CMLitLsPor22ow",
      "use": "sig",
      "kid": "2c3fac16b73fc848d426d5a225ac82bc1c02aefd",
      "e": "AQAB",
      "kty": "RSA"
    }
  ]
}

To get the kid, for example, is I have to do two foreach() before I can get the data:

foreach ($certs as $key => $val) {
    foreach($val AS $key2 => $val2){
        $kid = $val2->kid;      
    }
}

Is there a faster or a more standard way to get that data?

  • Possible duplicate of [PHP JSON Specific Key To Array](https://stackoverflow.com/questions/45531677/php-json-specific-key-to-array) – Rahul May 20 '19 at 10:11

2 Answers2

2

You can use array_column to get the kid from the array. First, you need to decode the JSON into an array and then use it as

$arr = json_decode($json, true);
print_r(array_column($arr['keys'],'kid'));

Live Demo

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
1

try this code,

 $json = json_decode($certs);
 foreach ($json->keys as $key => $value) {
       $kid= $value->kid;
   }

easy way to get kid value, using only one foreach().