使用php上的公共字段对json数据进行分组

时间:2016-02-22 16:29:10

标签: php sql json

我在向服务器执行sql查询(MYSQL)之后以json格式获取数据,我想以某种方式将关于具有通用名称的字段的数据分组。这是我处理数据的代码和我的结果执行查询后。

def access(request, instance):
    ...
    # explicitly pass instance as keyword argument to ReplyForm
    form  = ReplyForm(request.POST, instance=instance)
    ...

我得到的结果:

<?php

$serverName = "localhost";
$userName = "root";
$password = "root";
$database = "eshop";

// Create connection with the database
$conn = new mysqli($serverName, $userName, $password , $database);

//Retrieves the two values sent from the ajax request
$userName = $_GET["userName"];

// Check the status of the connection
if ($conn->connect_error)
{
    alert("The connection has timed-out!!!");
    die("Connection failed: " . $conn->connect_error);

}

else
{
    $data = new stdclass();
    $data->status = "";
    $past_orders = [];

    $previous_orders_sql =  mysqli_query($conn , 
     "SELECT order_products.order_id , order_date , product_id , price
      FROM   register , orders , order_products , products
      WHERE  register.user_id = orders.user_id
      AND    orders.order_id  = order_products.order_id
      AND    products.product_id = order_products.product_num
      AND    user_name = '$userName'");


    if(mysqli_num_rows($previous_orders_sql)>0)
    {

        $data->status = "OK";

        while($row = mysqli_fetch_array( $previous_orders_sql , MYSQLI_ASSOC))
        {
            $data-> past_orders[] = $row;
        }

    }

    else
    {
        $data->status = "Failed";
        mysqli_error($conn);
    }

}

echo json_encode($data);

?>

所以我希望能够将有关order_id的数据分组(因为order_id和order_date对于某些结果是相同的)并且具有以下内容:

{"past_orders":
[{"order_id":"1","order_date":"2012-12-27","product_id":"1","price":"12.40"},{"order_id":"1","order_date":"2012-12-27","product_id":"2","price":"32.00"},{"order_id":"1","order_date":"2012-12-27","product_id":"3","price":"25.00"},{"order_id":"3","order_date":"2016-01-12","product_id":"1","price":"12.40"},{"order_id":"3","order_date":"2016-01-12","product_id":"6","price":"28.00"},{"order_id":"3","order_date":"2016-01-12","product_id":"7","price":"37.00"},{"order_id":"4","order_date":"2014-04-06","product_id":"1","price":"12.40"},{"order_id":"4","order_date":"2014-04-06","product_id":"2","price":"32.00"},{"order_id":"4","order_date":"2014-04-06","product_id":"5","price":"13.50"}]}

如果答案需要任何额外代码,请通知我发布。

3 个答案:

答案 0 :(得分:2)

我会以这种方式重做你的while迭代:

    while ($row = mysqli_fetch_array($previous_orders_sql, MYSQLI_ASSOC)) {

        if (!isset($data->past_orders[$row['order_id']])) {
            $order_arr = array(
                "order_id" => $row['order_id'],
                "order_date" => $row['order_date']
            );
            $data->past_orders[$row['order_id']] = $order_arr;
        }

        $data->past_orders[$order['order_id']]['products'][] = array(
            "product_id" => $row['product_id'],
            "price" => $row['price']
        );
    }

这样你的结果就是这样一个很好的设置:

array (size=3)
  0 => 
    array (size=3)
      'order_id' => int 1
      'order_date' => string '2012-12-27' (length=10)
      'products' => 
        array (size=3)
          0 => 
            array (size=2)
              'product_id' => int 1
              'price' => float 12.4
          1 => 
            array (size=2)
              'product_id' => int 2
              'price' => float 32
          2 => 
            array (size=2)
              'product_id' => int 3
              'price' => float 25
  1 => 
    array (size=3)
      'order_id' => int 3
      'order_date' => string '2016-01-12' (length=10)
      'products' => 
        array (size=2)
          0 => 
            array (size=2)
              'product_id' => int 1
              'price' => float 12.4
          1 => 
            array (size=2)
              'product_id' => int 6
              'price' => float 28
  2 => 
    array (size=3)
      'order_id' => int 4
      'order_date' => string '2014-04-06' (length=10)
      'products' => 
        array (size=3)
          0 => 
            array (size=2)
              'product_id' => int 1
              'price' => float 12.4
          1 => 
            array (size=2)
              'product_id' => int 2
              'price' => float 32
          2 => 
            array (size=2)
              'product_id' => int 5
              'price' => float 13.5

此外,您的SQL查询效率不高。您应该使用JOINs代替:

SELECT o.order_id, o.order_date, p.product_id, p.price
FROM orders as o 
JOIN register as r ON r.user_id=o.user_id
JOIN order_products as op ON op.order_id=o.order_id
JOIN products as p ON p.product_id=op.product_num
WHERE r.username = '$userName'

答案 1 :(得分:0)

我知道您希望重新构建此数据结构,以便更轻松地使用它。简单的版本可能是这样的:

1

如果真的有必要,你可以进一步按摩这个阵列以获得你所需要的。

答案 2 :(得分:0)

在查询中添加另一行按ID排序,然后在where语句中放置内部where。像这样:

 $previous_orders_sql =  mysqli_query($conn , 
 "SELECT order_products.order_id , order_date , product_id , price
  FROM   register , orders , order_products , products
  WHERE  register.user_id = orders.user_id
  AND    orders.order_id  = order_products.order_id
  AND    products.product_id = order_products.product_num
  AND    user_name = '$userName'
  order by orders.order_id desc");


if(mysqli_num_rows($previous_orders_sql)>0)
{

    $data->status = "OK";

    while($row = mysqli_fetch_array( $previous_orders_sql , MYSQLI_ASSOC))
    {
        $idvar = $row[order_id];

        while($row = mysqli_fetch_array( $previous_orders_sql , MYSQLI_ASSOC))
            {
             if ($row[order_id] == $idvar)
             $data-> past_orders[] = $row[order_date].$row[product_id].$row[price] etc etc etc;
            }
    }

}