>我有一个从sql返回的数组,我需要将它们放入单独的字符串中以便在页面上使用。它不在数据库中的单行中,并列出用户拥有的所有文件夹。数据库中的示例 John 有一个红色文件夹、绿色文件夹、蓝色文件夹。我运行查询并使用 fetchAll 返回 john 的文件夹。我把它放在一个数组中。我可以回显数组,它输出红色文件夹绿色文件夹蓝色文件夹
如何获取数组并将其拆分为单独的字符串?
PHP代码
$query = "SELECT album_name FROM albums WHERE username = :username";
$query_params = array(
':username' => $email
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
echo 'Database Error, please try again.';
}
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
以下需要更正:
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
将上述内容更改为:
$post = array();
foreach( $rows as $row )
{
// $post = array(); // This line should not be here . It should be outside and above foreach
// The below echo is for test purpose . Comment it if you don't need it
echo $row["album_name"] ,' ';
// $post["album_name"] = $row["album_name"]; // This keeps assigning $row["album_name"] to same index "album_name" of $post . Eventually you will have only one value in $post
$post[] = $row["album_name"];
}
// $text = implode(",", $post); // With coma's as separator
$text = implode(" ", $post); // With blank's as separator
echo 'John has ' , $text;
请尝试在最后一行print_r($post);
。
请在每个旁边使用print_r($text),然后您将获得所有带有逗号的arry并从那里删除$post = arry,并放在foreach之上。我正在努力帮助你,愿这有帮助
谢谢阿南德
试试这个:
$post = array();
foreach ($rows as $row) {
array_push($post, 'album_name', $row["album_name"]);
}
$text = implode(",", $post);
echo $text;
没有助理版本:
$post = array();
foreach ($rows as $row) {
$post[] = $row["album_name"];
}
$text = implode(",", $post);
echo $text;
它只显示最后一个文件夹的原因是因为你在循环开始时做了"$post = array()"。它每次都会重置阵列...只需将其从循环中取出并放在 foreach 上方即可。
1:它只显示最后一个文件夹 http://php.net/manual/en/function.imThe 原因是因为你在循环开始时做了"$post = array()"。它每次都会重置阵列...只需将其从循环中取出并放在 foreach 上方即可。
编辑:
试试这样:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$post = array();
foreach ($rows as $key => $folder) {
array_push($post, $folder)
}
$text = implode(",", $post);