Basic implode foreach

2019-07-27 04:27发布

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条回答
在下西门庆
2楼-- · 2019-07-27 04:47

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.

查看更多
登录 后发表回答