0

This is a simple one but for some reason I can't get it to work. I have a JSON string that I am converting like this...

$results = json_decode($output);

This gives me this...

{
  "text": "Test Text",
  "truncated": false,
  "entities": {
    "media": [
      {
        "media_url": "http:\/\/pbs.twimg.com\/media\/34453543545.jpg",
        "media_url_https": "https:\/\/pbs.twimg.com\/media\/34453543545.jpg",
        "type": "photo",
        "sizes": {
          "thumb": {
            "w": 150,
            "h": 150,
            "resize": "crop"
          }
        }
      }
    ]
  }
}

I am trying to get the media_url like this...

$media_url = $results->entities->media_url;

But it is not working, have also tried...

$media_url = $results[entities][media_url];

But still no joy, where am I going wrong?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

2 Answers2

3

Media is an array, so you must access it like so.

<?php
$str = '{
  "text": "Test Text",
  "truncated": false,
  "entities": {
    "media": [
      {
        "media_url": "http:\/\/pbs.twimg.com\/media\/34453543545.jpg",
        "media_url_https": "https:\/\/pbs.twimg.com\/media\/34453543545.jpg",
        "type": "photo",
        "sizes": {
          "thumb": {
            "w": 150,
            "h": 150,
            "resize": "crop"
          }
        }
      }
    ]
  }
}';

$results = json_decode($str);

echo $results->entities->media[0]->media_url;

https://3v4l.org/s4u9X

Result:

http://pbs.twimg.com/media/34453543545.jpg


Additionally, if there are multiple elements in media then you could loop over them.

foreach ($results->entities->media as $item) {
    echo $item->media_url.PHP_EOL;
}

You could even use a generator, which will allow you to either pull out the first, or loop over them.

$media_url = function() use ($results) {
    foreach ($results->entities->media as $item) {
        yield $item->media_url;
    }
};

// get first
echo $media_url()->current();

// or loop
foreach ($media_url() as $item){
    echo $item;
}

https://3v4l.org/DQePR

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
2

media is array, so you need to access its elements as such. The proper reference looks like this:

$media_url = $results->entities->media[0]->media_url;
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • Well, likely they're supposed to *iterate* over the array, not just assume there's one and only one element… – deceze Feb 09 '18 at 08:38