Home > Mobile >  How do I output additional PHP nested array values?
How do I output additional PHP nested array values?

Time:04-23

Here's the output from my JSON feed:

"Data": [
    {
      "EventName": "EVENT NAME HERE",
      ...,
      "Items": [
        {
          "ItemId": 1460016,
          "ItemType": "Space",
          "Name": "Walking Track"
        },
        {
          "ItemId": 1460015,
          "ItemType": "Space",
          "Name": "Weight Room"
        },
        {
          "ItemId": 1464063,
          "ItemType": "Resource",
          "Name": "Fabric Chairs",
          "Qty": 10
        }
      ],
      ...
    },...

I'm able to output the EventName, etc. But how do I return a comma-separated list of item Names where the ItemType is 'Space'? Like this:

Walking Track, Weight Room

I've tried a number of combinations of PHP array functions -- but haven't been able to filter out the results.

Edit

Nagwa's response got me halfway there -- but it didn't filter for ItemType = 'Space'. I then added a conditional, but still had to remove blank values. Here's what I ended up with. It works -- but is there a better method that I'm overlooking?

foreach ($arr['Data'] as $event) {
    $locations = array_map(function($item) {
        if ($item['ItemType'] == 'Space') {
            return $item['Name'];
        }
    }, $event['Items']);
    $locationsList = implode(', ', array_filter($locations));
    print $locationsList;
}

CodePudding user response:

    $names = array_map(function ($arr){
            return $arr['Name'];
        }, $array['Data']['Items']);

    $namesList = implode(', ', $names);

    die($namesList);

CodePudding user response:

You can use array_walk() to build your list. For each item, if the ItemType is 'Space', append the Name to your list of spaces.

$spaces = [];
foreach ($arr['Data'] as $event) {
    $locations = array_walk(
        $event['Items'],
        function($item) use (&$spaces) {
            if ($item['ItemType'] == 'Space') {
                $spaces[] = $item['Name'];
            }
        }
    );
    $locationsList = implode(', ', $spaces);
    print $locationsList; // Walking Track, Weight Room
}
  • Related