关于php代码的服务问题

关于php代码的服务问题,php,mysql,json,dictionary,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 = $

我已经用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格式的结束字典中,如何删除这个
。你能推荐我吗。

首先,你不能在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 ']
}';
}
?>

您应该使用PHP内置的JSON格式函数,如

为了做出良好的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);
?>

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


试试这个

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\u encode
    而不是手动构建json字符串)。如果你想做的事情看起来过于困难,也许有更好的方法来解决这个问题
  • 热爱您的代码:空格、缩进和给变量起有意义的名称将大大提高代码的可读性。一两年后,你会感谢你自己(或阅读你代码的人)

将输出构建为数组并使用该函数。手动构建JSON是不必要的,并且将很难维护。
mysql\uu
库已被弃用,将从未来版本的PHP中删除。使用PDO或MySQLi等替代方案,并使用参数化保护自己免受安全问题的影响。
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);
?>
$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);