0

I am storing the IDs of names with implode() function and comma separated like 1,3. Column name is diet_id(varchar) and it has values 1,3. Now i want to fetch and display these IDs and their names like ID1 is ABC and ID2 is XYZ. I am using explode function to fetch and display but it returns me Array. Here is what i did so far

Fetching

<?php
$ShowProducts = mysqli_query($con, "SELECT * FROM food WHERE merchant_id='$userId'");
while($row=mysqli_fetch_assoc($ShowProducts)){
// Getting Names from IDs
$Diet_query     = mysqli_query($con,"SELECT * FROM diets WHERE id=".$row['diet_id']);
$main_diet      = mysqli_fetch_assoc($Diet_query);
$ar = explode(' ',$main_diet); 
?>

Now displaying

<td><?php echo $ar;?></td>

but it returns me Array

Team Thunder
  • 91
  • 2
  • 9

2 Answers2

1

explode() always returns an array. In your example the single values are 1 and 3 (exploded from 1,3). Therefore the array will have two fields. One with the value 1 and one with the value 3.

The text "Array" is the standard string representation of an array in PHP. If you want to print out the values individually you can use their indexes (starting with 0):

<td><?php echo $ar[0];?></td>
<td><?php echo $ar[1];?></td>

There also many many other ways how to display array data, also see this question for reference.

Side note: In your post you are exploding the values by space and not by comma, so you might want to change your call to the explode() function accordingly if the value is actually stored with a comma as you said:

$ar = explode(' ',$main_diet); 

should be:

$ar = explode(',',$main_diet); 
ArSeN
  • 5,133
  • 3
  • 19
  • 26
0

I checked my above query with var_dump(), it was bringing no data. When entry is only 1 in the table like 5, then it was showing data but with 3.5.2, it was showing null. changed my query to this

$sql = "SELECT * FROM food";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$ids = $row["diet_id"];
$sql = "SELECT * FROM diets WHERE id IN ($ids)";
$result = mysqli_query($con, $sql);
while ($drow = mysqli_fetch_assoc($result))
{
$diet_name[] = $drow['diet_full_name'];
}

and then

<td><?php echo implode(", ", $diet_name);?></td>

It worked then

Team Thunder
  • 91
  • 2
  • 9