如何从foreach中的每个数组中删除最后一个逗号?

时间:2017-08-20 03:52:44

标签: php arrays html-lists delimiter

我有一个多维数组,我正在尝试使用逗号分隔符并从每个数组中删除最后一个逗号到目前为止我尝试了这个。

$cars=array("Volvo","BMW","Toyota","Honda","Mercedes");
$chunks =(array_chunk($cars,2));
foreach ($chunks as $key) {
    echo "<ul>";
    $data = array();
    foreach ($key as $value) {
        $data[] ="<li>".$value."</li>".",";
    }
    rtrim($data, ",");
    echo "</ul>";
}
foreach ($data as $key ) {
    echo $key;
}

预期产出:

<ul>
    <li>Volvo,</li><li>BMW</li>
</ul>
<ul>
    <li>Toyota,</li><li>Honda</li>
</ul>
<ul>
    <li>Mercedes</li>
</ul>

请注意BMWHondaMercedes之后没有逗号。

3 个答案:

答案 0 :(得分:1)

根据您提供的示例代码,您所说的结果应该由以下内容生成:

$cars   = array( "Volvo","BMW","Toyota","Honda","Mercedes" );
$chunks = array_chunk( $cars, 2 );

for ( $i = 0; $i < count( $chunks ); ++$i ) {
    for ( $j = 0; $j + 1 < count( $chunks[ $i ] ); ++$j ) {
        $chunks[ $i ][ $j ] .= ',';
    }
}

现在$chunks包含您在评论中想要的多维数组以及每个非最后一个元素的注释。

答案 1 :(得分:1)

这是一种使用array_splice()而不是array_chunk()的不太循环的方法。没有count()调用,没有递增计数器,只有一个循环。

代码:(Demo

$cars=array( "Volvo","BMW","Toyota","Honda","Mercedes");
while($cars){                             // while there are still elements in the array...
    $chunk=array_splice($cars,0,2);       // extract first two elements (reducing $cars)
    if(isset($chunk[1])){$chunk[0].=',';} // add comma to 1st element if 2nd element exists
    $output[]=$chunk;                     // add extracted elements to multi-dim output
}
var_export($output);

输出:

array (
  0 => 
  array (
    0 => 'Volvo,',
    1 => 'BMW',
  ),
  1 => 
  array (
    0 => 'Toyota,',
    1 => 'Honda',
  ),
  2 => 
  array (
    0 => 'Mercedes',
  ),
)

您的无序列表的实现更简单 - 只需将逗号添加到</li><li>调用中的加入字符串implode(),</li><li>。这也改善了代码的多功能性和更大的“块”。 (而我的第一个代码仅适用于包含两个元素的子数组。)

代码:(Demo

$cars=array( "Volvo","BMW","Toyota","Honda","Mercedes");
while($cars){
    $chunk=array_splice($cars,0,2);
    echo "<ul><li>",implode(",</li><li>",$chunk),"</li></ul>";  // add comma to implode's glue string
}

输出:

<ul>
    <li>Volvo,</li><li>BMW</li>
</ul>
<ul>
    <li>Toyota,</li><li>Honda</li>
</ul>
<ul>
    <li>Mercedes</li>
</ul>

答案 2 :(得分:0)

假设您在视图文件中执行此操作,您可以执行以下操作:

$cars=array("Volvo","BMW","Toyota","Honda","Mercedes");

foreach (array_chunk($cars,2) as $chunk) {
    echo '<ul>', PHP_EOL;

    $keys = array_keys($chunk);
    $lastKey = array_pop($keys);
    foreach ($chunk as $key => $car) {
        echo '    ', '<li>', $car, $key !== $lastKey ? ',' : '', '</li>', PHP_EOL; 
    }

    echo '<ul>', PHP_EOL;
}

所以基本上我们在处理之前找到每个块的最后一个键,因此我们可以确定是否附加逗号。请注意,PHP_EOL' '等内容仅为格式添加,应删除。

这是working demo

虽然这种方法在视图中很好,但对于其他事情,最好先格式化数据然后再显示它(即在遍历数据时不应回显)。有点功能的例子是:

$cars=array("Volvo","BMW","Toyota","Honda","Mercedes");

$result = implode('', array_map(function ($items) { 
    $list = implode(',</li><li>', $items);

    return "<ul><li>$list</li></ul>";
}, array_chunk($cars,2)));

echo $result;