php - 如何从多行中检索值作为单个字符串

标签 php mysql arrays string

我制作了包含三列的MySQL数据库tags_id , tags , user_id ,它必须给出与 user_id 相关的所有标签。给定。

例如:对于此链接:“http://allwaysready.16mb.com/Cuboid/tagsTest.php?user_id[]=7

输出是:

{"result":[{"tags":"Pascol"},{"tags":"PHP"},{"tags":"Python"}]}

但我需要我的结果是这样的字符串:

{"result":[{"tags":"Pascol","PHP",","Python"}]}

它不应该在数组中,我希望它在单个字符串中。

这是我的 php 代码:

<?php 

if($_SERVER['REQUEST_METHOD']=='GET'){

    $user_id  = $_GET['user_id'];

    require_once('dbConnect.php');

    $user_tags = array();

    foreach ($_REQUEST['user_id'] as $key => $val) {
        $user_tags[$key] = filter_var($val, FILTER_SANITIZE_STRING);
    }
    $user_ids = "'" . implode("','", $user_tags) . "'";
    $sql = "SELECT * FROM user_tags WHERE user_id IN ({$user_ids})";

    $r = mysqli_query($con,$sql);

    //creating a blank array 
    $result = array();

    //looping through all the records fetched
    while($row = mysqli_fetch_array($r)){

        //Pushing name and id in the blank array created 
        array_push($result,array(
           "tags"=>$row['tags']
        ));
    }

    //Displaying the array in json format 
    echo json_encode(array('result'=>$result));

    mysqli_close($con);
}

我应该在代码中更改什么? 请帮助我,谢谢。

最佳答案

您的array_push的意思

使用 $key => $value 将新元素推送到数组

因此,这种情况下的解决方案是删除 array_push 并尝试

$result['tags'][] = $row['tags'];

关于php - 如何从多行中检索值作为单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38682500/

相关文章:

mysql - ['pmadb' ] 和 ['controlhost' ] 服务器配置有什么区别?

清理所有数据的 PHP 函数

python - 使用 numpy 从图像数组的 RGB 值获取 (x,y) 坐标值

php - 检测同时上传进程

php - 消息 : SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

mysql - 如何在不添加整列的情况下选择不同列的总和

arrays - Perl:我可以使用模式匹配来查找日志文件中的某些行吗

php - 嵌入随机命名的 MP3

php - 现有网站需要多个用户访问相同的数据

php - 用数组php中的空值替换空字符串