简体   繁体   中英

Get Specific Value from Multidimensional Associative JSON

I am trying to get a specific value from a JSON response and am having trouble figuring out how to target it. I can loop through it but I want to only output a single value based on the key as the response is dynamic and not always guaranteed to have the same output.

I have converted the JSON response to an array and here is an example of what I have at this point:

Array (
     [0] => Array (
         [rel] => advertisements
         [href] => https://api.teamsnap.com/v3/advertisements
     )
     [1] => Array (
         [rel] => active_season_team
         [href] => https://api.teamsnap.com/v3/teams
     )
     [2] => Array (
         [rel] => assignments
         [href] => https://api.teamsnap.com/v3/assignments
     )
     [3] => Array (
         [rel] => availabilities
         [href] => https://api.teamsnap.com/v3/availabilities
     ) 
)

I need to be able to echo the "href" value by the key "rel". I have tried:

foreach($links as $key => $value) {
  echo $key['advertisements'];
}

But need a way to say $links as $key->rel = $value->http (thats the logic I can come up with)

You can use array_search on the rel column (extracted using array_column ) to find the key of a matching value (eg advertisements ). If it exists, you can then access the value directly:

if(($key = array_search('advertisements', array_column($links, 'rel'))) !== false) {
    echo $links[$key]['href'];
}

Output

https://api.teamsnap.com/v3/advertisements

Demo on 3v4l.org

For more flexibility, you could write this as a function:

function get_link($links, $cat) {
    if(($key = array_search($cat, array_column($links, 'rel'))) !== false) {
        return $links[$key]['href'];
    }
    else {
        return '';
    }
}

echo get_link($links, 'active_season_team');

Output:

https://api.teamsnap.com/v3/teams

Demo on 3v4l.org

I didn't understand your requirements but as per syntax, In your case key will be index of array you can get data as below:

foreach($links as $link){
  echo $link['rel'].' = '.$link['href'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM