我已经在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格式的结束字典中如何删除这个,
。你能推荐我吗?
首先,JSON响应中不能有<br>
,除非该响应只是用于显示而非实际使用。
为了删除末尾的,
,您需要在一个变量中创建每个"行",您可以编辑而不仅仅是回显该行。
这里有一些代码可以实现这一点:
<?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 ']
}';
}
?>
您应该使用PHP内置的JSON格式化函数,如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);
?>
我认为应该这样做。我现在在日期/Price块的开头添加一个逗号,除了第一个(由新的$ct变量检查)之外的每个日期/Pric组合。
<?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);
$ct = 0;
while($re2=mysql_fetch_array($sql2)){
if ($ct > 0) { echo ', ';}
ct++;
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>}';
}
?>
尝试这个
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
$city=array();
while($re1=mysql_fetch_array($sq)){
$city['city'] = $re1['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)){
$city['city'] = array("date" => $re2["day"].'-'.$re2["month"].'-'.$re2["year"];
if($re2['price']==''){
$city['city'] = array('price'=>'--');
}else{
$city['city'] = array('price'=>$re2["price"]);
}
}
}
echo json_encode($city);
?>
欢迎使用堆栈溢出。与其用修改什么来修复代码来回答你的问题,不如用一个重构的代码版本来回答,其中包含我在开始用PHP编程时很想拥有的注释。希望这里有东西给你:
$month = 10;
$year = date('Y');
// 1. You can get the data you're after in a single query using a LEFT JOIN.
// In your original code you run one database query for every city, which
// quickly slows down the program as you add more cities. This change is
// mostly for keeping the code clean in this case, but in practice it's
// good to avoid unnecessary back and forth with the database.
//
// 2. The MySQL DATE data type opens up a lot of functionality in your queries
// that isn't available when storing day, month and year in separate columns.
//
// 3. The mysql_* functions are deprecated and no longer exist in PHP 5.5.0,
// so you ideally shouldn't be using them (see the red box in the docs):
//
// http://php.net/manual/en/function.mysql-query.php
//
// I've opted to demo PDO with a parameterised query as I like it, but you
// could use the mysqli_* functions instead. The following pretends that
// $connection is an instance of PDO. The variable `$stmt` stands for
// 'statement'. Further info on PDO:
//
// http://php.net/manual/en/class.pdo.php
// http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
//
$stmt = $connection->prepare(
'SELECT
city.name AS city,
price.price,
DATE_FORMAT(price.date, '%d-%m-%Y') AS date
FROM city
LEFT JOIN price ON price.city_id = city.id
WHERE MONTH(price.date) = :month AND YEAR(price.date) = :year
ORDER BY DAY(price.date) ASC'
);
$stmt->bindValue(':month', $month);
$stmt->bindValue(':year', $year);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// This short array syntax is valid in PHP 5.4 and higher.
// If you're using 5.3 or lower, `[]` would be `array()`
$output = [];
foreach ($results as $row) {
$output[$row['city']] = [
'date' => $row['date'],
'price' => $row['price'] ?: '--'
];
}
json_encode($output);
一般说明:
- 数据库非常强大:在许多情况下,在查询中组织数据比在PHP代码中组织数据更简单、更快
- 保持简单:尽量用最简单的方式实现(例如
json_encode
,而不是手动构建JSON字符串)。如果你想做的事情看起来过于困难,也许有更好的方法来解决这个问题 - 喜欢您的代码:空白、缩进和为变量提供有意义的名称将大大提高代码的可读性。一两年后,你会感谢自己(或阅读你代码的人)