我有一个从sql返回的数组,我需要将它们分成单独的字符串才能在页面上使用。它不在数据库中的单行中,并列出用户拥有的所有文件夹。 数据库中的示例john有一个红色文件夹,绿色文件夹,蓝色文件夹。 我运行查询并使用fetchAll返回john的文件夹。我把它放在一个数组中。我可以回显数组并输出redfoldergreenfolderbluefolder
如何获取数组并将其拆分为单独的字符串?
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)
答案 0 :(得分:1)
以下需要更正:
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;
答案 1 :(得分:0)
在最后一行尝试print_r($post);
。
答案 2 :(得分:0)
它只显示最后一个文件夹的原因是因为你在循环开始时执行“$ 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);
答案 3 :(得分:0)
请在每个侧面使用print_r($ text),然后您将获得所有arry with commos 并从那里删除$ post = arry并将foreach放在上面。 我想帮助你,也许这有帮助
感谢 阿南德
答案 4 :(得分:0)
试试这个:
$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;