sanjay joon
sanjay joon

Reputation: 133

php multi level foreach loop remove last comma from loop

hii i have 2 level foreach loop like this and i want to remove last comma from each loop ,

/* 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 "] , ";
}

output of this program :

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

And i want like this

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

i am already use implode , trim but is remove only one loop not remove second . sol me my problem , thanks .

Upvotes: 1

Views: 458

Answers (3)

Ernesto Jr Montejo
Ernesto Jr Montejo

Reputation: 33

I have my own version in removing "," at the end and instead of adding a "."

$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

Upvotes: 0

BitSmith
BitSmith

Reputation: 116

You can turn the problem around and add the ',' to the start of the next output. There is no need to remove it afterwards.
However you don't want the comma for the first output.

$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
}

Upvotes: 1

dougtesting.net
dougtesting.net

Reputation: 571

Rather than output the information directly you could put it in to a variable as a string. This will allow you to rtrim the last comma after the loop, then echo the information.

// 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;

Upvotes: 0

Related Questions