Basic implode foreach

吃可爱长大的小学妹 提交于 2019-12-11 07:37:03

问题


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);
?>

回答1:


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.



来源:https://stackoverflow.com/questions/10160315/basic-implode-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!