简体   繁体   English

更改我的输出格式

[英]change my output format

my php code is : 我的PHP代码是:

$q = $db->query("SELECT username FROM users LIMIT 3");
$users = array();
while($row = $db->fetchAll($q))
{
    $users[] = $row;
}


foreach($users as $user)
{


echo $user['username'].'<br>';

}

and the output will be 和输出将是

Nilsen
Michael
Sam

Does it possible to change my output format to be Nilsen,Michael,Sam without start foreach ? 是否可以在不启动foreach的情况下将输出格式更改为Nilsen,Michael,Sam

Any idea please ? 有什么想法吗?

Thank you. 谢谢。

while($row = $db->fetchAll($q)) // fetchAll is wired here, but since you get the result, asume that's right
{
    $users[] = $row['username'];
}

then use: 然后使用:

echo join(',' $users);

you can use GROUP_CONCAT() and loop won't be needed on the php side. 您可以使用GROUP_CONCAT()并且php端不需要循环。

SELECT GROUP_CONCAT(username) user_name FROM users LIMIT 3
$q = $db->query("SELECT username FROM users LIMIT 3");
while($row = $db->fetchAll($q))
{
   print_r($row);
}

.

or 要么

 echo $row[0], $row[1], $row[2]; 

I wouldn't recommend this for production though, just for checking/debuging.. 我不建议将其用于生产,仅用于检查/调试。

Mostly for debugging you can use like this : 通常,对于调试,您可以这样使用:

$q = $db->query("SELECT username FROM users LIMIT 3");
while($row = $db->fetchAll($q))
{
    print_r($row); // or below
    var_dump($row);
}

The var_dump() function displays structured information about variables/expressions including its type and value. var_dump()函数显示有关变量/表达式的结构化信息,包括其类型和值。 Arrays are explored recursively with values indented to show structure. 递归地探索数组,并缩进显示结构的值。 It also shows which array values and object properties are references. 它还显示了哪些数组值和对象属性是引用。

The print_r() displays information about a variable in a way that's readable by humans. print_r()以人类可读的方式显示有关变量的信息。 array values will be presented in a format that shows keys and elements. 数组值将以显示键和元素的格式显示。 Similar notation is used for objects. 类似的符号用于对象。

Do you mean this? 你是这个意思吗

$stmt = $db->query('SELECT username FROM users LIMIT 3');

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$users = array_map(function($row) {
    return $row['username'];
}, $rows);

print_r($users);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM