Search code examples
phparraysjsonjsondecoder

Echo part of two dimentional json array


I have a nested json array at

$sdata['my_server']['server_ips'];

Whose result looks like this

{ "ip_address": [ { "access": "private", "address": "x.x.x.x", "family": "IPv4" }, { "access": "public", "address": "xxxx:xxxx:xxxx:xxx:xxxx:xxxx:xxxx:xxxx", "family": "IPv6" }, { "access": "public", "address": "xxx.xxx.xxx.xxx", "family": "IPv4", "part_of_plan": "yes" } ] }

I only want t show value of ipv4 ip address in access public part means this one

"address": "xxx.xxx.xxx.xxx"

Is there any idea on it? Thanks


Solution

  • You can use array_filter with json_decode

     $r = array_filter(json_decode($json, true)['ip_address'], function($v){
      return ($v['family'] === 'IPv4' && $v['access'] === 'public');
     });
    

    Working example :- https://3v4l.org/k0M0V

    print_r($r) will give you an array, you can use array_shift and than use $r['address']. If there are multiple values than use array_column by address and use implode.