【问题标题】:How to combined two Select queries' outputs in to one JsonObject in a same php?如何在同一个 php 中将两个 Select 查询的输出合并到一个 JsonObject 中?
【发布时间】:2016-03-30 09:53:19
【问题描述】:

我的 php 中有两个选择查询。

$rr=mysql_query("SELECT * FROM tbl_sales_target WHERE rep = '502' AND DATE_FORMAT(date, '%Y-%m') = '2016-03'"); 
$r=mysql_query("SELECT SUM(tbl_sales.ton_ach/1000) AS tonSum, SUM(tbl_sales.val_ach/1000000) AS valSum FROM tbl_sales INNER JOIN tbl_mas_customer on tbl_sales.customer = tbl_mas_customer.customer WHERE rep = '502' AND DATE_FORMAT(date, '%Y-%m') = '2016-03'");

我想将每个查询输出合并到一个 Json 中。 这是我的两个查询的 Json 输出

{"feed":[{"rep":"502","date":"2016-03-01","val_tar":"64.91","ton_tar":"84.59","col_tar":"69.92"}]}{"feed":[{"tonSum":"45.201940","valSum":"33.150250"}]}

我想要的是这样的。

{"feed":[{"rep":"502","date":"2016-03-01","val_tar":"64.91","ton_tar":"84.59","col_tar":"69.92","tonSum":"45.201940","valSum":"33.150250"}]}

这是我的 php 脚本。

$r=mysql_query("select sum(tbl_sales.ton_ach/1000) as tonSum, sum(tbl_sales.val_ach/1000000) as valSum from tbl_sales inner join tbl_mas_customer on tbl_sales.customer = tbl_mas_customer.customer where rep = '502' and DATE_FORMAT(date, '%Y-%m') = '2016-03'");

$rr=mysql_query("select * from tbl_sales_target where rep = '502' and DATE_FORMAT(date, '%Y-%m') = '2016-03'");     
    $result = array();
    $resultt = array();
        while($row=mysql_fetch_array($rr)){
        array_push($result,
        array('rep'=>$row[0],           'date'=>$row[1],'val_tar'=>$row[2],'ton_tar'=>$row[3],'col_tar'=>$row[4]));}

        while($row=mysql_fetch_array($r)){
        array_push($resultt,
        array('tonSum'=>$row[0],
       'valSum'=>$row[1]));}

        $json['feed']= $result;
                echo json_encode($json);

        $jsonn['feed']= $resultt;
                echo json_encode($jsonn);    

我的桌子

已编辑

$r=mysql_query("SELECT  tbl_sales_target.*,
        SUM(tbl_sales.ton_ach/1000) AS tonSum, 
        SUM(tbl_sales.val_ach/1000000) AS valSum 
FROM tbl_sales_target 
JOIN tbl_mas_customer ON tbl_mas_customer.rep = tbl_sales_target.rep
JOIN tbl_sales ON tbl_sales.customer = tbl_mas_customer.customer
WHERE tbl_sales_target.rep = '502' 
AND DATE_FORMAT(date, '%Y-%m') = '2016-03'");

    $result = array();

        while($row=mysql_fetch_array($r)){
        array_push($result,
        array('rep'=>$row[0],
       'date'=>$row[1],'val_tar'=>$row[2],'ton_tar'=>$row[3],'col_tar'=>$row[4],'tonSum'=>$row[5],'valSum'=>$row[6]));}

        $json['feed']= $result;
                echo json_encode($json);
enter code here

输出

 {"feed":[{"rep":"502","date":"2016-03-01","val_tar":"64.91","ton_tar":"84.59","c‌​ol_tar":"69.92"},{"tonSum":"45.201940","valSum":"33.150250"}]} 

我想要什么

{"feed":[{"rep":"502","date":"2016-03-01","val_tar":"64.91","ton_tar":"84.59","c‌​ol_tar":"69.92","tonSum":"45.201940","valSum":"33.150250"}]} 

安卓方法

 private void getJsonRequest(final Button a, final Button b, final Button c) {

        DateFormat df = new SimpleDateFormat("yyyy-MM");
        final String systemDate = df.format(new Date());

        final SQLiteHandler sqLiteHandler = new SQLiteHandler(getApplicationContext());
        Cursor cr = sqLiteHandler.getData(sqLiteHandler);
        cr.moveToFirst();

        do {
            repNo = cr.getString(0);
        } while (cr.moveToNext());
        cr.close();

        CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_REP_SUMMERY, hashMap, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject jsonObject = new JSONObject(String.valueOf(response));
                    if (jsonObject.names().get(0).equals("feed")) {
                        productSummList = parseJsonResponse(response);

                        txtTarget.setText(productSummList.get(0).getTar_ton() + " MT");
                        double tar_ton = Double.parseDouble(productSummList.get(0).getTar_ton());
                        int intTar_ton = (int) tar_ton;
                        arcProgress.setMax(intTar_ton);

                        arcProgress.setFinishedStrokeColor(Color.GREEN);
                        arcProgress.setStrokeWidth(20f);
                        arcProgress.setBottomTextSize(35f);
                        arcProgress.setBottomText("Ton");
                        ObjectAnimator animation = ObjectAnimator.ofInt(arcProgress, "progress", 0, 30); // see this max value coming back here, we animale towards that value
                        animation.setDuration(1500); //in milliseconds
                        animation.setInterpolator(new DecelerateInterpolator());
                        animation.start();

                        a.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                txtTarget.setText(productSummList.get(0).getTar_ton() + " MT");
                                arcProgress.setBottomText("Ton");
                                ObjectAnimator animation = ObjectAnimator.ofInt(arcProgress, "progress", 0, 30);
                                animation.setDuration(1500);
                                animation.setInterpolator(new DecelerateInterpolator());
                                animation.start();
                            }
                        });

                        b.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                txtTarget.setText(productSummList.get(0).getTar_col() + " Mil");
                                arcProgress.setBottomText("Collection");
                            }
                        });

                        c.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                txtTarget.setText(productSummList.get(0).getTar_val() + " Mil");
                                arcProgress.setBottomText("Value");
                            }
                        });
                        //Toast.makeText(getApplicationContext(), "System Date " + systemDate, Toast.LENGTH_SHORT).show();
                        //Toast.makeText(getApplicationContext(), "Database Date " + productSummList.get(0).getTar_ton(), Toast.LENGTH_SHORT).show();
                        //Log.d("Database Date ", productSummList.toString());

                    } else {
                        Toast.makeText(getApplicationContext(), "No Data Available", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                productSummList = parseJsonResponse(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            protected Map<String, String> getParams() throws AuthFailureError {
                hashMap = new HashMap<String, String>();
                hashMap.put("rep_no", repNo);
                hashMap.put("systemDate", systemDate);
                return hashMap;
            }
        };
        requestQueue.add(request);
    }



private ArrayList<ProductSummery> parseJsonResponse(JSONObject response) {
        ArrayList<ProductSummery> productSumList = new ArrayList<>();
        if (response != null || response.length() > 0) {

            try {

                JSONArray arrayProduct = response.getJSONArray(KEY_FEED_NAME);

                for (int i = 0; i < arrayProduct.length(); i++) {
                    JSONObject currentObject = arrayProduct.getJSONObject(i);
                    String repName = currentObject.getString(KEY_REP_ID);
                    String date = currentObject.getString(KEY_DATE);
                    String valTar = currentObject.getString(KEY_VALUE_TARGET);
                    String tonTar = currentObject.getString(KEY_TON_TARGET);
                    String colTar = currentObject.getString(KEY_COL_TARGET);

                    ProductSummery productSummery = new ProductSummery();
                    productSummery.setRepNo(repName);
                    productSummery.setDate(date);
                    productSummery.setTar_val(valTar);
                    productSummery.setTar_ton(tonTar);
                    productSummery.setTar_col(colTar);

                    productSumList.add(productSummery);

                }
                //Toast.makeText(getApplicationContext(), productSumList.toString(), Toast.LENGTH_LONG).show();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return productSumList;
    }

新的 PhP 脚本............

<?php
error_reporting(-1);

 require_once 'include/Config.php';

$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
    mysqli_select_db($con,DB_DATABASE) or die("db selection failed");


    $r=mysqli_query($con,"SELECT  tbl_sales_target.*,
        SUM(tbl_sales.ton_ach/1000) AS tonSum, 
        SUM(tbl_sales.val_ach/1000000) AS valSum 
FROM tbl_sales_target 
JOIN tbl_mas_customer ON tbl_mas_customer.rep = tbl_sales_target.rep
JOIN tbl_sales ON tbl_sales.customer = tbl_mas_customer.customer
WHERE tbl_sales_target.rep = '502' 
AND DATE_FORMAT(date, '%Y-%m') = '2016-03'");


    $result = array();

        while($row=mysqli_fetch_array($r)){
        array_push($result,array('rep'=>$row[0],'date'=>$row[1],'val_tar'=>$row[2],'ton_tar'=>$row[3],'col_tar'=>$row[4],'tonSum'=>$row[5],'valSum'=>$row[6]));}


        $json['feed']= $result;
                echo json_encode($json);


    mysqli_close($con); 


?>

这是错误

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\ceat_sap\rep_summery_test.php on line 32
{"feed":[]}

【问题讨论】:

  • 能否请您发布示例。 tbl_salestbl_mas_customer 的数据。您需要在第一个查询中使用连接
  • 你为什么不只是简单地选择具有第二个查询的列?而不是 2 个查询。
  • 它没有用。我尝试对三个表使用内部联接。它没有用.. [我的桌子][1] [1]:i.stack.imgur.com/zJTB6.jpg
  • 为什么table_sales_target 没有关系? foreign keyprimary key 的关系在哪里?
  • table_sales_target 没有主键。值重复

标签: php android mysql json


【解决方案1】:

我认为这应该可以解决问题

$feed = array("feed" => array_merge($result, $resultt));
echo json_encode($feed);

见:http://php.net/manual/en/function.array-merge.php

另一种方法是将 2 个查询简单地合并为 1 个。

SELECT  tbl_sales_target.*,
        SUM(tbl_sales.ton_ach/1000) AS tonSum, 
        SUM(tbl_sales.val_ach/1000000) AS valSum 
FROM tbl_sales_target 
JOIN tbl_mas_customer ON tbl_mas_customer.rep = tbl_sales_target.rep
JOIN tbl_sales ON tbl_sales.customer = tbl_mas_customer.customer
WHERE tbl_sales_target.rep = '502' 
AND DATE_FORMAT(tbl_sales.date, '%Y-%m') = '2016-03'
AND DATE_FORMAT(tbl_sales_target.date, '%Y-%m') = '2016-03'

【讨论】:

  • 它不工作...这个错误来了... 警告:mysql_fetch_array() 期望参数 1 是资源,在 C:\xampp\htdocs\ceat_sap\rep_summery_test 中给出的布尔值。第 31 行的 php {"feed":[]}
  • 对于第一个答案,它实际上是给出一个输出,但它不像我提到的那样在一个 json 中。它给了我这样的东西 {"feed":[{"rep":"502","date":"2016-03-01","val_tar":"64.91","ton_tar":"84.59"," col_tar":"69.92"},{"tonSum":"45.201940","valSum":"33.150250"}]} 我不需要 },{ 在两个 json 之间
  • 不确定您对查询做了什么,它应该可以工作。同样对于第一个答案,我很确定它应该可以工作。你确定你回显了 json_encode($feed) 吗?也许添加代码,这样我就可以看到你做了什么。
  • 我更新了它....第一个工作正常。但是我想要没有 },{ 的 json 在 "69.92" 和 "tonSum" 之间...跨度>
  • 我明白,但 array_merge 函数不可能在它们之间留下逗号。您可以将代码发送到您使用第一个解决方案的地方吗?我不完全确定第二种解决方案出了什么问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
相关资源
最近更新 更多