0

I know it may seem a little confusing for a title but lets say I had this:

{"success":true,"name":"test","ips":[{"public":"ipaddr","local":"ipaddr"},{"public":"ipaddr","local":"ipaddr"}],"time":1040}

Since there are two "public" ip addresses, I only want to display the first public ip in the list. How would I go about doing that?

This is what I have so far:

$json = json_decode($contents, true);
foreach($json['ips'] as $item) {
    echo $item['public'];
}
user2255552
  • 33
  • 1
  • 4
  • 6
    http://php.net/break - and also `var_dump()` is your friend. This did work for me: `json_decode($json)->ips[0]->public` -- Also some classic guide: [Able to see a variable in print_r()'s output, but not sure how to access it in code](http://stackoverflow.com/a/6322173/367456) – hakre Apr 07 '13 at 21:45
  • 1
    If you want to output just 1 item of an array, you don't really need a loop, you can just access it directly: `echo $json['ips'][0]['public'];` But if you want to keep the loop, just put a `break;` after the first iteration. – Quasdunk Apr 07 '13 at 21:47
  • @user2255552: Please select the answer that helped you get it to work. That will mark your question as solved. – hakre Apr 07 '13 at 22:09

2 Answers2

1

Lets visualize the structure of your json data, then see how we can access a particular element (first ips) in the example below:

$json = <<<JSON
{
  "success": true,
  "name": "test",
  "ips": [
    {
      "public": "ipaddr",
      "local": "ipaddr"
    },
    {
      "public": "ipaddr",
      "local": "ipaddr"
    }
  ],
  "time": 1040
}
JSON;

$decoded = json_decode($json);

var_dump($decoded);
var_dump($decoded->ips[0]->public);
Volkan
  • 2,212
  • 1
  • 14
  • 14
0

Try

$json = json_decode($contents, true);
echo $json['ips'][0]['public'];

Example

peterm
  • 91,357
  • 15
  • 148
  • 157