1

我正在寻找回显数组的逗号分隔元素,例如:

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()或以其他方式在行的每个第二个元素之后换行?

4

7 回答 7

3
<?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);
于 2013-05-27T09:07:14.700 回答
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++;
}
于 2013-05-27T09:01:08.600 回答
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(",");}
}
?>
于 2013-05-27T09:07:11.433 回答
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)));

在线演示

于 2013-05-27T09:11:20.640 回答
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++;
}
?>
于 2013-05-27T09:15:06.703 回答
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));
于 2013-05-27T09:06:03.990 回答
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;
?>

如果您确实需要该数组,请先创建它并根据需要在上面进行修改。

于 2013-05-27T09:11:46.660 回答