0

我有一个从 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)
4

5 回答 5

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;
于 2013-10-04T03:34:55.090 回答
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; 
于 2013-10-04T03:41:35.947 回答
0

它只显示最后一个文件夹的原因是因为您在循环开始时执行了“$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);
于 2013-10-04T03:34:37.983 回答
0

试试print_r($post);你的最后一行。

于 2013-10-04T03:29:18.470 回答
0

请在 for each 中使用 print_r($text),然后您将获得所有带有 commos 的 arry 并从那里删除 $post = arry 并放在 foreach 的上方。我正在努力帮助你,希望能帮到你

谢谢阿南德

于 2013-10-04T03:37:35.387 回答