Home > Software design >  How to print an entire PHP array in a single HTML cell?
How to print an entire PHP array in a single HTML cell?

Time:09-23

I have a HTML table where there are some columns. Each column is showing its own value. But in one cell of the table, I want to display an entire array of item-names separated by commas. I want the table cell to display like this:

User ID Item Name
1 name1, name2, name3,....

$allitemnames holds the array values like name1, name2, name3 etc

This is my current code for fetching the array of items:


$itemnames="SELECT item_name FROM orderhistory WHERE uid='$userid' AND payment_mode = 'Cash'";
$itemnamescon=$con->query($itemnames);
$allitemnames=array();
while($x = mysqli_fetch_assoc($itemnamescon))
{
     $allitemnames[]=array('item_name'=> $x['item_name']);
}
$itemsarrayresult = implode(", ", $allitemnames);

It's fetching the array properly because when I try to Echo out the $allitemnames outside the HTML table then it prints the whole array. But the main problem arises when i try to print it in a HTML table cell. I used the following code to print it:

echo"<tr style='color:white; background-color:#262626'>
<td><center>".$userid."</center></td>
<td><center>".$itemsarrayresult."</center></td>
</tr>";

This code does print multiple names in a single cell but the output is not at all what I want. It prints only "Array, Array, Array...."

Firstly it shows this warning message many times and it says-

Warning: Array to string conversion in C:\xampp\htdocs\Project\pendingpayments.php on line 62

and secondly the table looks like this:

User ID Item Name
1 Array, Array, Array,....

I've had a look online but every forum I've come across has been people trying to loop through and print 1 value per td, not all values in one td.

Sorry for my poor English.

If anyone is able to help out here I would greatly appreciate it, thanks in advance!

CodePudding user response:

There is an multidimension array. You don't need her. Do like this:

$allitemnames[] = $x['item_name'];

CodePudding user response:

A couple of different approaches to this:

In php:

while($x = mysqli_fetch_assoc($itemnamescon))
{
     $allitemnames[]=$x['item_name'];
}
$itemsarrayresult = implode(", ", $allitemnames);

In MySQL:

SELECT GROUP_CONCAT(item_name) FROM orderhistory WHERE uid='$userid' AND payment_mode = 'Cash'"

CodePudding user response:

can you change your code as following and retry?

$itemsarrayresult = '';
while($x = mysqli_fetch_assoc($itemnamescon))
{
     $itemsarrayresult .= $x['item_name'].",";
}
echo '<tr style="color:white; background-color:#262626">
    <td><center>'.$userid.'</center></td>
    <td><center>'.rtrim($itemsarrayresult,',').'</center></td>
   </tr>';
  • Related