[英]data of separate PHP array with comma
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: 您可以为此使用array_column :
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 在这里,我们只按键对元素进行分组(在本例中为
val
),然后内爆分解返回的数组
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]);
使用
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: 在
for
look里面也是一个问题,这意味着,您用逗号将数组内插,您可以按照@Rakesh的建议进行操作:
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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.