关于服务php代码的问题

时间:2014-11-01 06:57:37

标签: php mysql json dictionary

我已经在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格式结束字典中如何删除此,。你能建议我吗。

4 个答案:

答案 0 :(得分:1)

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

为了在最后删除,,您需要每个&#34;行&#34;在您可以编辑的变量中创建,而不仅仅是回显该行。

以下是一些可以实现这一目标的代码:

<?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);
?>

答案 1 :(得分:0)

我认为应该这样做。我现在在日期/价格块的开头添加一个逗号,每个日期/价格组合除了第一个(由新的$ ct变量检查)。

 <?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>}';
}
?>

答案 2 :(得分:0)

试试这个

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);
?>

答案 3 :(得分:0)

欢迎使用Stack Overflow。而不是回答你的问题,确切地说要修改代码的内容,这里有一个重构版本的代码,其中包含我在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字符串)。如果您尝试做的事情看起来过于困难,可能有更好的方法来解决问题。
  • 喜欢你的代码:空格,缩进和赋予变量有意义的名称将大大提高代码的可读性。一年或两年后,你会感谢自己(或有人读你的代码)。