我制作了包含三列的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/