how to separate array with commas?

左心房为你撑大大i 提交于 2019-12-11 06:09:20

问题


i have this $_categories as array()

<?php print_r($_categories); ?> is this: Array ( [0] => 13 [1] => 7 )

what i need is to extract de values 13 and 7 into this format: 13,7 (without comma after the last value).

i have this code but is not there yet... the result is: 137 and not 13,7

<?php
    if ( is_array($_categories) ) {
        foreach ($_categories as $key => $value) {
            $out = array();
            array_push($out, $value);
            echo implode(', ', $out);
        }
    }
    else {
        echo '<li>There are no saved values yet.</li>';
    }
?> 

Thanks, nelson


回答1:


Directly use

echo implode(', ', $_categories);



回答2:


Everytime you are implodeing just one element,and echoing just it. Try like this:

$out = array();   //putting outside of the loop
foreach ($_categories as $key => $value) {
    array_push($out, $value);
}    
echo implode(', ', $out);   //putting outside of the loop


来源:https://stackoverflow.com/questions/11671733/how-to-separate-array-with-commas

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