Implode()数组并在两个元素之后创建新行

时间:2013-05-27 08:53:08

标签: php arrays foreach newline implode

我希望回显数组中逗号分隔的元素,例如:

Element1, Element2, Element3, Element4, Element5, Element6

但是,为了保持回声元素的整洁,我可能需要在每行的每个第二个元素之后转到一个新行,例如

Element1, Element2,
Element3, Element4,
Element5, Element6

我正在做的事情:

<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) { 
    $labels_array[] = $label['name'];
    }  
echo implode(' ,', $labels_array); 
?>

显然得到了:

Element1, Element2, Element3, Element4, Element5, Element6

如何使用implode()或其他方式在行的每个第二个元素后执行换行?

7 个答案:

答案 0 :(得分:2)

<?php

$labels = array('Element1', 'Element2', 'Element3', 'Element4', 'Element5', 'Element6');

# Put them into pairs
$pairs_array = array_chunk($labels, 2);

# Use array_map with custom function
function joinTwoStrings($one_pair) {
  return $one_pair[0] . ', ' . $one_pair[1];
}

$pairs_array = array_map('joinTwoStrings', $pairs_array);

echo implode(',' . PHP_EOL, $pairs_array);

答案 1 :(得分:1)

未经测试,但这样的事情应该有效

$i = 1;

foreach($labels as $label) {
   echo $label;

   // add a comma if the label is not the last
   if($i < count($labels)) {
      echo ", ";
   }

   // $i%2 is 0 when $i is even
   if($i%2==0) {
       echo "<br>"; // or echo "\n";
   }    
   $i++;
}

答案 2 :(得分:1)

<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) { 
    $labels_array[] = $label['name'];
    }

for($i=0;$i<count($labels_array);$i++)
{ echo($labels_array[$i]);
  if($i % 2 != 0)
  {
     echo("\n");
  }else{echo(",");}
}
?>

答案 3 :(得分:1)

为了幻想:

$labels_array=array("Element 1","Element 2","Element 3","Element 4","Element 5","Element 6");
echo implode(",\n",array_map(function($i){ // change to ",<br />" for HTML output
    return implode(", ",$i);
},array_chunk($labels_array,2)));

Online demo

答案 4 :(得分:1)

您可以使用foreach来实现它,我为您粘贴代码,它将为您提供所需的输出

<?php
$labels = array("Element1", "Element2", "Element3", "Element4", "Element5","Element6");
$key = 1;
$lastkey = sizeof($labels);
foreach($labels as $value)
{
  if($key%2)
  {
    if($key==$lastkey)
    {
      echo $value;
    }
    else
    {
      echo $value.",</br>";
    }
  }
  else
  {
     if($key==$lastkey)
     {
        echo $value."</br>";
     }
     else
     {
        echo $value.",</br>";
     }
  }
  $key++;
}
?>

答案 5 :(得分:0)

$i = 1;
$str = '';
foreach($labels AS $label)
{
    $str += "$label, ";
    if ($i % 2 == 0)
    {
        $str += "\n";
    }
    $i++;
}
//Remove last 2 chars
$str = substr($str,0,(strlen($str)-2));

答案 6 :(得分:0)

除非您需要其他内容的数组,否则只需构建字符串...

<?php
$labels = Requisitions::getLabelNames($id);
$s='';
$i=0;
$l=count($labels);
foreach($labels as $label){
    $s.=$label['name'];
    // Append delimeter. Makes sure every second, and the last one, will be a line break
    $s.=((++$i%2)&&($l!=$i))?' ,':"\n";  
}
echo $s;
?>

如果您确实需要某个数组,请先创建它并根据需要修改它。