我的页面上有一个名为$recipe['ingredients'];的变量

在var中,您具有以下内容,

牛奶100毫升,奶油350毫升,水150毫升

等等。现在,我试图将其拆分为如下所示

<ul>
    <li>100ml milk</li>
    <li>350ml double cream</li>
    <li>150ml water</li>
</ul>


到目前为止,我有以下代码,

$ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
$ingredients = array($ingredientsParts);
while (! $ingredients) {
   echo" <li>$ingredients</li>";
}


但是由于某种原因,它不起作用,而且我没有爆炸修复的经验。

最佳答案

当您对字符串进行explode()时,它将自动转换为数组。您无需像第二行那样将其转换为数组类型。
您要使用foreach()循环遍历数组,而不是while循环。

   $ingredientsAry = explode(',', $row_rs_recipes['ingredients']);
   foreach($ingredientsAry as $ingredient){
       echo "<li>$ingredient</li>";
   }



实际上,您可以对explode()值执行一个foreach()循环

foreach(explode(',', $row_rs_recipes['ingredients']) as $ingredient){
    echo "<li>$ingredient</li>";
}

关于php - PHP-将数组拆分为多个块。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9190262/

10-12 12:50
查看更多