laravel嵌套foreach 3级

时间:2018-06-20 05:46:54

标签: php laravel foreach response

我正在使用一个api,我需要按如下方式返回数据。

var fruitData = {};

var key = "red-fruits";
fruitData[key] = red;

var key2 = "green-fruits";
fruitData[key2] = green;

var key3 = "yellow-fruits";
fruitData[key3] = yellow;

var key4 = "purple-fruits";
fruitData[key4] = purple;

var fruitString = JSON.stringify(fruitString);

$.ajax({
    method: "fruit-post", 
    type: "POST",
    url: "LINK",
    data: {
        "data": fruitString
    },
    cache: false,
    success: function(data) {
}

我使用以下方法

{
  "Gamelist": {
    "MarketList": {
      "SelectionList": {}
    }
  }
}

该项目具有这样的关系。一个游戏有很多市场。一个市场有很多选择。我需要像上面的json格式一样获取这些。我怎样才能做到这一点?我正在使用以下foreach结构。

        $eventId = 1;
        $sportId = 1;
        $leagueId = 1;

        $events = $this->baseEvents->filterEventsBy($sportId, $eventId, $leagueId);

        //get all the markets for events
        $eventMarkets = $this->baseMarkets->getAllMarketsByEventId($events->pluck('s_base_event_id'));

        //get all the selections for market
        $marketSelections = $this->baseSelections->getAllSelectionsByMarketId($eventMarkets->pluck('s_base_market_id'));

请求的功能

foreach ($events as $event) {
        $markets = $eventMarkets->where('s_base_event_id', $event->s_base_event_id);
        foreach ($markets as $market) {
            $selections = $marketSelections->where('s_base_market_id', $market->s_base_market_id);
            foreach($selections as $selection){

            }
        }
    }

1 个答案:

答案 0 :(得分:1)

格式化阵列数据,请尝试

$data = [];

$eventId = 1;
$sportId = 1;
$leagueId = 1;

$events = $this->baseEvents->filterEventsBy($sportId, $eventId, $leagueId);

//get all the markets for events
$eventMarkets = $this->baseMarkets->getAllMarketsByEventId($events->pluck('s_base_event_id'));

//get all the selections for market
$marketSelections = $this->baseSelections->getAllSelectionsByMarketId($eventMarkets->pluck('s_base_market_id'));

foreach($events as $index => $event){
    forach($eventMarkets as $indx => $market){
        foreach($marketSelections as $section){
            if($section->s_base_market_id == $market->id && $market->s_base_event_id == $event->id){
              $data['GameList'][$index]['MarketList'][$indx]['SelectionList'][] = $section->toArray();
            }
        }
    }
}

$jsonData = json_encode($data);