我正试图将一个对象数组传递到视图,然后使用刀片模板引擎对它们进行循环。
数据是从Parse.com查询返回的,其结构如下:
[
{
"Params": [],
"difficulty": "Medium",
"exerciseDescription": "Sit on a gym ball with a dumbbell in each hand. Bend your elbows to lift the dumbbells to your shoulder.",
"exerciseID": "1024",
"exerciseName": "Bicep Curl Sitting on Gym Ball",
"images": [
2758,
2759,
2760
],
"objectId": "9xjQ4WVo6e",
"tags": [
"Dumbbell",
"Gym Ball",
"Flexion"
],
"words": [
"seated",
"dumbbell",
"arm",
"curl"
]
}
]
我使用这个查询得到这个:
public function about()
{
$programmeId = 'T8iqZhtDqe';
$query = new ParseQuery("PrescribedProgrammes");
try {
$programme = $query->get($programmeId);
// The object was retrieved successfully.
} catch (ParseException $ex) {
echo $ex;
// The object was not retrieved successfully.
// error is a ParseException with an error code and message.
}
$exerciseData = $programme->get("exerciseData");
$programmeTitle = $programme->get("prescribedProgrammeTitle");
// return view('pages.about', compact('exerciseData','programmeTitle'));
return view('pages.about')->with('exerciseData', $exerciseData);
}
为了测试这一点,我一直在尝试:
@foreach($exerciseData as $exercise => $value)
{{ $exercise->exerciseName }}
@endforeach
然而,我得到了一个Array to string conversion
错误。来自angularJS背景,我希望将我的对象数组传递到视图中,然后在我认为合适的时候循环穿过它们。这会被认为是糟糕的形式吗?
编辑
运行dd($exerciseData)
array:7 [▼
0 => array:9 [▼
"Params" => []
"difficulty" => "Medium"
"exerciseDescription" => "Sit on a gym ball with a dumbbell in each hand. Bend your elbows to lift the dumbbells to your shoulder."
"exerciseID" => "1024"
"exerciseName" => "Bicep Curl Sitting on Gym Ball"
"images" => array:6 [▶]
"objectId" => "9xjQ4WVo6e"
"tags" => array:6 [▶]
"words" => array:8 [▶]
]
1 => array:9 [▶]
2 => array:9 [▶]
3 => array:9 [▶]
4 => array:9 [▶]
5 => array:9 [▶]
6 => array:9 [▶]
]
我认为您使用的是数组的键,而不是值。例如,默认的PHP foreach如下所示:
foreach($array as $key => $value) {
// code
}
编辑:查看$exerciseData的转储后,PHP似乎正在将JSON序列化为一个数组,因此这改变了答案。
如果您将其返回到视图:
return view('quiz.create', compact('programmeTitle', 'exerciseData'));
然后在你看来,它应该可以工作,因为我已经在本地测试了它:
<h2>{{$programmeTitle}}</h2>
@foreach ($exerciseData as $key => $exercise)
<p>{{$exercise['exerciseName']}}</p>
@endforeach