PHP Laravel预先从api迭代json数据

时间:2017-07-17 18:37:37

标签: php json laravel api foreach

因此,我对PHP和Laravel非常陌生,并且很难尝试使用foreach循环来获取数字'和'步骤'内部分析说明'阵列。我能够获得' title' readyInMinutes'和'指令'但无法获得“分析说明”中的任何内容。

这里是json的dd:

{#203 ▼
  +"id": 602534
  +"title": "Bok Choy with Ground Chicken Stir Fry"
  +"readyInMinutes": 15
  +"image": "https://spoonacular.com/recipeImages/Bok-Choy-with-Ground-Chicken-Stir-Fry-602534.jpg"
  +"instructions": "In a wok or large saute pan over high heat, add the cooking oil. When hot, add ground chicken and saute until browned (but not fully cooked through). Lower heat ▶"
  +"analyzedInstructions": array:1 [▼
    0 => {#558 ▼
      +"name": ""
      +"steps": array:4 [▼
        0 => {#559 ▼
          +"number": 1
          +"step": "In a wok or large saute pan over high heat, add the cooking oil. When hot, add ground chicken and saute until browned (but not fully cooked through). Lower heat ▶"
          +"ingredients": array:5 [▶]
          +"equipment": array:2 [▶]
        }
        1 => {#567 ▶}
        2 => {#573 ▶}
        3 => {#576 ▶}
      ]
    }
  ]
}

我的控制器与我的api /键:

    public function selectedrecipe($id){
        $response = Unirest::get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/" . $id . "/information?includeNutrition=true",
            array(
                "X-Mashape-Key" => " KEY ",
                "Accept" => "application/json"
            )
        );

        return view('search.show')->withSelected($response->body);
    }

我试图循环以获得数字'和'步骤' “步骤”的内部'并将它们列在我的刀片中。

显示刀片:

@extends('layouts.app')

@section('content')
    <h1>{{ $selected->title }}</h1>
        <div id="recipeInfo">
            <img class="recipeImg" src="{{ $selected->image }}"/>
                <div class="recipeText">
                    <h2>Instructions</h2>
                    <p>Total Time: {{ $selected->readyInMinutes }} minutes</p>
                    <p>{{ $selected->instructions }}</p>

                    {{$selected->sourceUrl}}

                    @foreach($selected->analyzedInstructions[0]->steps[0]->number as $select)
                        {{$select}}
                    @endforeach
                </div>
        </div>
@endsection

1 个答案:

答案 0 :(得分:0)

您正在获取数组的特定索引而不是迭代它们,这将导致您只打印一个结果。

 ( (?&hh_mm) )                 # (1), hh:mm
 -                             # -
 ( (?&hh_mm) )                 # (2), hh:mm

 (?:                           # Optional 
      ,                             # ,
      ( (?&hh_mm) )                 # (3), hh:mm
      -                             # -
      ( (?&hh_mm) )                 # (4), hh:mm
 )?
 (?(DEFINE)
      (?<hh_mm>                    
           (?: [01] \d | 2 [0-3] )
           :
           [0-5] \d 
      )                            
 )

这将迭代遍历数组中的每个元素及其子元素。