我有一个名为“Recipes”的数据库表,该表中有一列名为“ingredients”。这些成分来自浏览器中的 HTML 输入。我要求用户通过按回车键并跳到下一行来分隔每种成分。我遇到的问题是,当我在 show.blade.php 页面上返回此数据时,它作为一个长字符串返回。我一直无法弄清楚如何将它作为列表返回。
例子:
在我调用成分数据的网站部分,我得到“燕麦牛奶香蕉肉桂枫糖浆”。
我想得到
- 燕麦
- 牛奶
- 香蕉
- 肉桂
- 枫糖浆
我正在使用 Laravel 5.7 构建应用程序,我正在调用 {{$recipe->ingredients}}。 PHP explode() 函数有点乱,但没有运气。我不是很有经验所以我确定这不是一个难以解决的问题,我似乎无法在网上找到任何东西。也许我没有正确地提出问题?
我的 create.blade.php 文件的代码是:
<div class="createRecipeBody">
<fieldset>
<small class="errorMessage">{{ $errors->first('title') }}</small>
<label for="title">Give your creation a title</label>
<input type="text" name="title" id="title">
</fieldset>
<fieldset>
<small class="errorMessage">{{ $errors->first('description') }}</small>
<label for="description">Describe your creation</label>
<textarea name="description" id="description"></textarea>
</fieldset>
<fieldset>
<small class="errorMessage">{{ $errors->first('ingredients') }}</small>
<label for="ingredientList">List the ingredients</label>
<textarea name="ingredients" id="ingredientList" placeholder="Please list each ingredient on a seperate line"></textarea>
</fieldset>
<fieldset>
<small class="errorMessage">{{ $errors->first('directions') }}</small>
<label for="ingredientList">Directions</label>
<textarea name="directions" id="directions" placeholder="Please list each step on a seperate line"></textarea>
</fieldset>
<div class="terms">
<label class="authenticationCheck">
<input class="termsOfService" type="checkbox">
<span>
Public Recipe
</span>
</label>
<label class="authenticationCheck">
<input class="termsOfService" type="checkbox">
<span>Private Recipe</span>
</label>
</div>
<button class="submitRecipe" type="submit">Share your creation</button>
</div>
</section>
这是我的 show.blade.php:
<h2>Ingredients</h2>
<span class="ingredients">
<span class="ingredientItem firstItem">
<span><i class="far fa-clock"></i> {{$recipe->prepTime}}</span>
</span>
<span class="ingredientItem">
<span><i class="fas fa-concierge-bell"></i> {{$recipe->servings}}</span>
</span>
<span class="ingredientItem">
<span><i class="fas fa-weight"></i> {{$recipe->calories}}</span>
</span>
</span>
<hr>
<p>Here's what you will need...</p>
<div>
<ol>
<li> {{$recipe->ingredients}}</li>
</ol>
</div>
<br>
<h2>Directions</h2>
<hr>
<p>{{$recipe->directions}}</p>
<h2>Chef's Tip</h2>
<hr>
<p>This feature is not yet enabled</p>
</div><!-- col-sm-6 -->
最佳答案
$string = 'apple banana cinemon pokemon';
$arr = explode(' ', $string);
array_walk($arr, function (&$item, $key) {
$item = $key+1 . '.) ' . $item;
});
$output = implode("\n", $arr);
是这样的吗? 首先,我将字符串分解为单个单词。 然后我将项目更改为您要求的格式。 然后我将元素连接成一个字符串。
编辑:列表现在从 1 开始
关于php - 如何从数据库行中获取项目列表并在 Laravel 中返回列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081874/