[英]Change a PHP array into separate strings
我有一个从sql返回的数组,我需要将它们分成单独的字符串以在页面上使用。 它不在数据库的单行中,并列出了用户拥有的所有文件夹。 约翰数据库中的示例有一个红色文件夹,绿色文件夹,蓝色文件夹。 我运行查询并使用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)
以下需要更正:
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);
在最后一行。
之所以只显示最后一个文件夹,是因为您在循环开始时执行了“ $ post = array()”。 每次都会重置数组...只需将其移出循环并将其置于foreach之上即可。
1 : http : //php.net/manual/en/function.im之所以只显示最后一个文件夹,是因为您在循环开始时执行了“ $ post = array()”。 每次都会重置数组...只需将其移出循环并将其置于foreach之上即可。
编辑:
这样尝试:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$post = array();
foreach ($rows as $key => $folder) {
array_push($post, $folder)
}
$text = implode(",", $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;
没有assoc ver:
$post = array();
foreach ($rows as $row) {
$post[] = $row["album_name"];
}
$text = implode(",", $post);
echo $text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.