gpt4 book ai didi

php - 服务 php 代码问题

转载 作者:行者123 更新时间:2023-11-29 12:36:35 25 4
gpt4 key购买 nike

我已经在 php 中创建了服务,但我遇到了一些问题,这是我实现的代码

 <?php
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
while($re1=mysql_fetch_array($sq)){
$id = $re1['id'];
$city = $re1['city'];
$city_id = $re1['id'];
echo '{ <br>"'.$city.'" : [ <br>';

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY day ASC';
$sql2=mysql_query($sql);
while($re2=mysql_fetch_array($sql2)){
echo '{ <br>';
echo '"date" : "'.$re2["day"].'-'.$re2["month"].'-'.$re2["year"].'",<br>';

if($re2['price']==''){ echo "Price : -- , <br>";}
else{
echo '"Price" : "'.$re2["price"].'" <br>';
}
echo '}, <br>';
}
echo ']<br>}';
}
?>

响应 json 格式如下。

{
"Ahmedabad" : [
{
"date" : "1-10-2014",
"Price" : "353"
},
{
"date" : "2-10-2014",
"Price" : "353"
},
{
"date" : "3-10-2014",
"Price" : "327"
},
]
}

但是在 json 格式结尾字典中如何删除这个 , 。你能建议我吗?

最佳答案

首先你不能拥有<br>在 JSON 响应中,除非该响应仅用于显示而不用于实际使用。

为了删除 ,最后,您需要在可以编辑的变量中创建每条“行”,而不仅仅是回显该行。

下面是一些可以实现这一点的代码:

<?php
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
while($re1=mysql_fetch_array($sq)){
$id = $re1['id'];
$city = $re1['city'];
$city_id = $re1['id'];
echo '{
"'.$city.'" : [
';

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY day ASC';
$sql2=mysql_query($sql);
while($re2=mysql_fetch_array($sql2)){
$line = '{
';

$line.= '"date" : "'.$re2["day"].'-'.$re2["month"].'-'.$re2["year"].'",
';

if($re2['price']=='')
{
$line.= "Price : -- ,
";
}
else
{
$line.= '"Price" : "'.$re2["price"].'"
';
}
$line.= '},';
echo $line;
}
$line = substr($line,0,-1);
echo ']
}';
}
?>

您应该使用内置 JSON 格式化函数的 PHP,例如 json_encode()

为了做出良好的 JSON 响应,您需要正确处理数据以避免格式错误。

所以这段代码更好地利用了 PHP 和 MySQL:

<?php
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
while($re1=mysql_fetch_array($sq)){
$id = $re1['id'];
$city = $re1['city'];
$city_id = $re1['id'];

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY day ASC';
$sql2=mysql_query($sql);
while($re2=mysql_fetch_array($sql2)){
// create each line in the city
$line["date"] = $re2["day"].'-'.$re2["month"].'-'.$re2["year"];

if($re2['price']=='')
{
$line["Price"] = "--";
}
else
{
$line["Price"] = $re2["price"];
}

// add the line to the city
$cities[$city][] = $line;
}
}
// encode to json
json_encode($cities);
?>

关于php - 服务 php 代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26686949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com