based on a query:
$query = $db->query("SELECT id, email, status, enviados FROM
contactos LIMIT 0,500");
where I get emails and store them in an array I want to separate them and print them by commas and then put them in a variable, where the result is something like:
$ variable = a1, a2, a3;
I try to do with implode but it does not work, I was already seeing the other issues but I can not find a solution
this is my code
$query = $db->query("SELECT id, email, status, enviados FROM
contactos LIMIT 0,500");
$count = $query->num_rows;
while($row = mysqli_fetch_array($query)){
$datos_seleccionados[] = array(
'emails' => $row['email']
);
}
for ($i = 0; $i <= $count; $i++) {
echo implode(",", $datos_seleccionados[$i]);
}
You need to do it in this way
$datos_seleccionados = [];
while($row = mysqli_fetch_array($query))
{
$datos_seleccionados[] = $row['email'];
}
echo implode(",", $datos_seleccionados);
You can use array_column for this:
example code:
$data = [
['title' => 'foo', 'val' => 1],
['title' => 'bar', 'val' => 5],
['title' => 'foobar', 'val' => 9]
];
echo implode(',', array_column($data, 'val'));
here we just group the elements by the key (in this case val
) and then just implode that returned array
so in your case:
echo implode(',', array_column(mysqli_fetch_array($query), 'email'));
Its not working because you are storing your data into multidimensional array here:
$datos_seleccionados[] = array(
'emails' => $row['email']
);
Using echo implode(",", $datos_seleccionados[$i]);
inside a for
look also an issue, it means, you are imploding an array with comma, you can just do it as @Rakesh suggested:
Solution (i am using this code with some optimization) :
if($count > 0){ // if count exist
$datos_seleccionados = array(); // initiate
while($row = mysqli_fetch_array($query)){
$datos_seleccionados[] = $row['email'];
}
echo implode(",",$datos_seleccionados);
}
else{
echo "No result found";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.