基本内爆foreach [英] Basic implode foreach

查看:197
本文介绍了基本内爆foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码,我想回显用逗号分隔的数组元素。代码输出错误列表,但没有逗号。我错过了什么?


$ $ p $ <?php
$ array = get_field('casts');
$ elements = $ array;

foreach($ array as $ key => $ value){
echo implode(',',$ value)};
?>

编辑1:其中 code>是嵌套数组。

编辑2: pre class =lang-php prettyprint-override> <?php
$ array = get_field('casts');
$ new_array = array();
foreach($ array as $ sub_array){
foreach($ sub_array as $ value){
array_push($ new_array,$ value);


echo implode(,,$ new_array);
?>


解决方案

为什么要分配 $ elements = $ array; 然后从不使用 $ elements



不需要循环( foreach )来破坏数组。



试试这个:

 <?php 
$ array = get_field('casts');
$ new_array = array();
foreach($ array as $ sub_array){
foreach($ sub_array as $ value){
//这个array_push()函数将$ value添加到$ new_array的末尾。
array_push($ new_array,$ value);


echo implode(,,$ new_array);
?>

以下是 implode()

玩游戏并测试上面的代码这里



下一次,添加标签 php ,否则我们的代码将不会获得颜色语法。


I have the following code of which I want to echo array elements separated by commas. The code outputs the disered list, but without commas. What am I missing?

<?php 
    $array    = get_field('casts');
    $elements = $array;

    foreach($array as $key => $value) {
        echo implode(', ', $value)};
?>

EDIT 1: where $elements are nested arrays.

EDIT 2: Working snippet:

<?php 
    $array = get_field('casts');
    $new_array = array();
    foreach($array as $sub_array) {
        foreach($sub_array as $value) { 
            array_push($new_array, $value);
        }
    }
    echo implode(", ", $new_array);
?>

解决方案

Why are you assigning $elements = $array; and then never using $elements?

Also you don't need to loop (foreach) to implode an array.

Try this:

<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
    foreach($sub_array as $value) {
        // this array_push() function adds $value to the end of $new_array.
        array_push($new_array, $value);
    }
}
echo implode(", ", $new_array);
?>

Here is the documentation on implode()

You can play around and test the above code here.

Also next time, add the tag php, otherwise our codes won't get color syntax.

这篇关于基本内爆foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆