在php中回显时创建一个数组列表

在php中回显时创建一个数组列表

问题描述:

我想从数据库中回显我的结果,并使它们看起来像数组.它们不一定必须是数组,而是看起来像一个数组.即当我回显我的结果时,

I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,

我希望我的最终结果看起来像

i would want my final result to look like

[10,200,235,390,290,250,250]

当我尝试以下代码时:

$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);

echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {

   $list =  $row['column'];
   $listwithcoma = "$list,";  
   echo ltrim($listwithcoma,','); 
}
echo ']' 

结果是:

[10,200,235,390,290,250,250,]

您做错了. ltrim($ listwithcoma,',')无效.

ltrim -从字符串开头删除空格(或其他字符)

ltrim — Strip whitespace (or other characters) from the beginning of a string

您可以尝试使用 implode 的简单方法.

You can try a simple way with implode.

$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
   $list[] =  $row['column'];
}

echo '[' . implode(',', $list) . ']';