1

In PHP, how can I return JSON elements values in a string separated by commas?

This is how I'm calling the "list" JSON file in PHP:

$list = file_get_contents('http://example.com/list/json');
$items = json_decode($list, true);

This is the List JSON content (may contain more items, and more columns for each, not only itemID):

{
 "resultCount":3,
 "results": [
{"itemId":1223604159},
{"itemId":1231618623},
{"itemId":1244303880}]
}

So I want this string as response:

1223604159,1231618623,1244303880

Already tried implode without success:

$IdByCommas = implode(',',$items->results->itemId);
Eric
  • 65
  • 2
  • 9

1 Answers1

3

As every item of $items->results is an array with one key itemId you can't simply implode($items['results']). You have to get every value of itemId.

With php5.5/5.6/7, where you have array_column function, you can:

echo implode(',', array_column($items['results'], 'itemId')));

Otherwise you have to extract every value of itemId:

$ids = [];
foreach ($items['results'] as $item) {
    $ids[] = $item['itemId'];
}
echo implode(',', $ids);

Also, I'm using [] instead of -> because you decoded json to array, not object.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • My JSON file may contain other columns in each item, not only itemID. I put only itemID to make simpler to understand.. I'm not getting it to work with your suggestion... – Eric Aug 05 '17 at 21:14