[英]php codeigniter data base query
i want to answer like this 我想这样回答
["Badin","Bahawalnagar","Bahawalpur"] [“ Badin”,“ Bahawalnagar”,“ Bahawalpur”]
but when i run query 但是当我运行查询时
if ($result->num_rows() > 0)
{
echo '[';
foreach($result->result() as $listing)
{
echo '"'.$listing->city_name.'"';
if ($listing->city_name!='')
{
echo ',';
}
}
echo ']';
}
then i got an extra coma in the last plz help me out to remove this 然后我在最后一个昏迷了一个额外的昏迷帮助我删除此
i want remove last coma ["Badin","Bahawalnagar","Bahawalpur",] 我要删除最后的昏迷[“ Badin”,“ Bahawalnagar”,“ Bahawalpur”,]
You code should look like this: 您的代码应如下所示:
if ($result->num_rows() > 0)
{
echo '[';
foreach($result->result() as $key => $listing)
{
$row = $key+1;
if ($listing->city_name != '')
{
echo '"'.$listing->city_name.'"';
// If it's not last item, then add a comma
if ($row < $result->num_rows())
{
echo ',';
}
}
}
echo ']';
}
I assumed also, that you don't want to echo the city name if it's empty, otherwise you'd end up with empty ""
. 我还假设,如果城市名称为空,则您不希望回显城市名称,否则最终将以空的
""
结束。
Your output suspiciously similar to json, maybe a straight json_encode() is enough once you get the city names: 您的输出可疑地类似于json,一旦您获得城市名称,也许直接使用json_encode()就足够了:
$cities = array();
foreach($result->result() as $listing) {
$cities = $listing->city_name;
}
$cities = array_values(array_filter($cities)); // removes the empty ones, reset the indexes
echo json_encode($cities);
Also, you could use implode() for concatenation like this too: 同样,您也可以像这样使用implode()进行串联:
echo '["'.implode('","', $cities).'"]';
You can use json_encode to do this 您可以使用json_encode来执行此操作
if($result->num_rows > 0){
foreach ($result->result_array() as $row){
$new_row['label']=htmlentities(stripslashes($row['user_name']));
$new_row['val']=htmlentities(stripslashes($row['user_id']));
$row_set[] = $new_row; //build an array
}
echo json_encode($row_set); //format the array into json data
}
you can concat your results into a variable and trim rightmost ",". 您可以将结果合并为变量,并在最右边修剪“,”。
if ($result->num_rows() > 0)
{
$my_result = '';
echo '[';
foreach($result->result() as $listing)
{
$my_result .= '"'.$listing->city_name.'"';
if ($listing->city_name!='')
{
$my_result .= ',';
}
}
$my_result = rtrim($my_result , ",");
echo $my_result;
echo ']';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.