如何在foreach循环中使用implode函数

时间:2015-10-06 09:57:38

标签: php

我想在从db.eg:location1,location2,location3等提取的每个记录之间显示“,(逗号)”

<table class="table table-striped table-condensed table-hover">
<?php 
    //var_dump($volunteer_panel_location);
    echo "<tr>"
       . "<td class='col-xs-4'>Interview Location </td>"
       . "<td>";
    foreach ($volunteer_interview_location as $vlocations)
    {
        echo "{$vlocations->location}";
    }
    echo "</td></tr>"
       . "<tr>"
       . "<td>Panel Location </td>"
       . "<td>";
    foreach ($volunteer_panel_location as $plocations)
    {
        echo "{$plocations->location}";
    }
    echo "</td>"
       . "</tr>";
?>
</table>

我试过这个,但记录重复了

$pp=array();
foreach ($volunteer_panel_location as $plocations)
{
    $pp[]=$plocations->location;
    echo implode(",",$pp);
}

3 个答案:

答案 0 :(得分:1)

试试这个

$locations = [];
foreach ($volunteer_panel_location as $plocations)
{
    $locations[] = $plocations->location;
}
echo implode(",",$locations);

答案 1 :(得分:1)

$ar='';   
for ($i=0; $i <count($data) ; $i++) {
    $ar[]=$data[$i]->id;
}
$rt=implode(',',$ar);
echo $rt;

$data替换为您的数据。

$ar是一个数组。

我建议在foreach函数之外调用implode。

答案 2 :(得分:0)

试试这个

echo implode(",",$volunteer_panel_location);