how to store database values in an array with comma seperated values
I am looking to store the database values which are already stored as id's and retrieve via a for each loop within an array.
I have tried something like this, but it is not working:
foreach ($list as $item)
{
$commaSeparated = implode(',' , $item['id');
}
echo $commaSeparated;
Where item['id']
is the specific column pulled out of the query. If I use the $list variable, then I am getting the full result of the query which I do not want.
But, my error results in this:
Warning: implode(): Invalid arguments passed
This is what has correctly returned what I need:
foreach 开发者_Go百科($list as &$id)
{
$listArr[] = $id['toolbar_id'];
$commaSeparated = implode(',' , $listArr)
echo $commaSeparated;
That happens because you need to perform
$commaSeparated = implode(',' , $list);
It is not a good practice though. You should never store the lists as comma-separated items in database. Instead - create additional table for it and store 1 item per row.
The second argument to implode
needs to be an array. Try this:
$commaSeparated = implode(',', $list);
Implode function accepts a separator and an array for parameters. Then you should do this:
$commaSeparated = implode(',' , $list);
echo $commaSeparated;
(Source: http://php.net/manual/pt_BR/function.implode.php)
You need to do more checks to avoid the error if your data is not in correct format.
if(is_array($list)){
foreach ($list as $item)
{
if(is_array($item))
$commaSeparated = implode(',' , $item);
}
echo $commaSeparated;
}
I suggest you trying a var_dump($variable) where $variable is the ...variable, in which the data is stored, knowing its structure will tell you what data to expect and how to iterate over it.
精彩评论