php多级foreach循环删除循环中的最后一个逗号

时间:2017-09-06 00:23:27

标签: php arrays foreach trim implode

我有这样的2级foreach循环,我想删除每个循环中的最后一个逗号,

/* Here is the mysql query */
foreach($loop1 as $val1){
   $showvalone = $val1['data1'];
   echo "[".$showvalone;
   /*  Here is the second MySQL query connected with 1st query */
   foreach($loop2 as $val2){
      $showvaltwo[] = $val2['data2'];
   }
   echo implode(",",$showvaltwo); 
   echo "] , ";
}

该程序的输出:

[ 1
  one ,
  two ,
  three
],
[ 2
  one ,
  two ,
  three
],

我想要这样

[ 1
  one ,
  two ,
  three
],
[ 2
  one ,
  two ,
  three
]

我已经使用implode,trim但是只删除一个循环而不是删除第二个。 解决我的问题,谢谢。

3 个答案:

答案 0 :(得分:1)

您可以解决问题并将“,”添加到下一个输出的开头。之后无需将其删除 但是,您不希望第一个输出使用逗号。

$addComma = ''; // should be empty for the first lines.
foreach($loop1 as $val1){
   $showvalone = $val1['data1'];
   echo $addComma."[".$showvalone;
   /*  Here is the second MySQL query connected with 1st query */
   foreach($loop2 as $val2){
      $showvaltwo[] = $val2['data2'];
   }
   echo implode(",",$showvaltwo); 
   echo "]";
   $addComma = " , "; // any lines following will finish off this output
}

答案 1 :(得分:0)

不是直接输出信息,而是将其作为字符串放入变量中。这将允许您在循环后rtrim最后一个逗号,然后回显信息。

// Declare variable to hold the string of information.
$values = "";

/* Here is the mysql query */
foreach($loop1 as $val1)
{
   $showvalone = $val1['data1'];
   $values .= "[".$showvalone;

   /*  Here is the second MySQL query connected with 1st query */
   foreach($loop2 as $val2)
   {
      $showvaltwo[] = $val2['data2'];
   }

   $values .= implode(",",$showvaltwo); 
   $values .= "] , ";
}

// Remove the last comma and spaces from the string.
$values = rtrim($values, ' , ');

// Output the information.
echo $values;

答案 2 :(得分:0)

我有一个自己的版本,即在结尾处删除“,”而不是添加“。”。

$numbers = array(4,8,15,16,23,42);

/* defining first the "." in the last sentence instead of ",". In preparation for the foreach loop */

$last_key = end($ages);

// calling the arrays with "," for each array.
foreach ($ages as $key) :
  if ($key === $last_key) {
    continue; // here's the "," ends and last number deleted.
  }
  echo $key . ", ";
endforeach;

echo end($ages) . '.' ; // adding the "." on the last array