Jump to content

constructing a string to be placed into an array


Darkmatter5

Recommended Posts

I have an array value that is 1,2,14.

Then I have code that will split those values using "," as the seperator and places the values into another array.  Then I have code that gets a string based on that those values and outputs that string to the page, but I really want to take that string to be placed in another array and seperate each new string with ", ".  How can I do this?

 

I'm basically wanting to convert "1,2,14" into "apples, oranges, lemons" and apply it to the original array $row['fruits'].  You'll see below.

 

<?php
$result=mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
  $fru_ids=explode(",",$row['fru_id']);
  foreach($fru_ids as $fru_id) {
    $query1="SELECT name FROM fruits WHERE fruit_id=$fru_id";
    $result2=mysql_query($query1) or die(mysql_error());
    $fru=mysql_fetch_array($result2);
    echo $fru['name'];
  }
}
?>

<?php

$result=mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
  $fru_ids=explode(",",$row['fru_id']);
  $query1="SELECT name FROM fruits WHERE fruit_id IN($fru_id) ORDER BY fruit_id";
  $result2=mysql_query($query1) or die(mysql_error());
  $fruits = array(); // reset array.
  while ($row2 = mysql_fetch_assoc($result2)) {
      $fruits[] = $row2['name'];
  }
  $row['fruits'] = implode(", ", $fruits);
}
?>

 

I think that is what you want.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.