简体   繁体   English

使用PHP和MySQL的自定义JSON数组

[英]Custom JSON array using PHP and MySQL

I use PHP to encode json data from my MySQL table, the output comes like this 我使用PHP对MySQL表中的json数据进行编码,输出如下所示

[
    {
    "Copra_Crushed_MT": "2306.01851",
    "Oil_Extracted_MT": "1454.9442"
    },
    {
    "Copra_Crushed_MT": "1234",
    "Oil_Extracted_MT": "5678"
    },
    {
    "Copra_Crushed_MT": "1907",
    "Oil_Extracted_MT": "4605"
    }
 ]

But i want the structure to be this way, how should i proceed to get this 但我希望结构是这种方式,我应该如何继续进行操作

[
  [2306.01851,1454.9442],
  [1234,5678],
  [1907,4605]
]

my PHP code used to encode JSON 我的PHP代码用于编码JSON

private function productionhourlys(){   
        if($this->get_request_method() != "GET"){
            $this->response('',406);
        }
        $query="SELECT distinct c.Copra_Crushed_MT, c.Oil_Extracted_MT FROM productionhourlys c order by c.productionhourlyNumber desc";
        $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);

        if($r->num_rows > 0){
            $result = array();
            while($row = $r->fetch_assoc()){
                $result[] = $row;
            }
            $this->response($this->json($result), 200); // send user details
        }
        $this->response('',204);    // If no records "No Content" status
    }

private function json($data){
        if(is_array($data)){
            return json_encode($data);
        }
    }

Put array_values around your row: array_values放在您的行周围:

$result[] = array_values($row);

( array_values docs ) array_values docs

Alternatively (and probably the better way) - You can use mysqli_result::fetch_row instead of fetch_assoc 或者 (可能是更好的方法)-您可以使用mysqli_result::fetch_row而不是fetch_assoc

while($row = $r->fetch_row()) {

( fetch_row docs ) fetch_row docs

json_encode in php will automatically turn associative arrays into json object (the curly brace syntax). php中的json_encode会自动将关联数组转换为json对象(大括号语法)。 You can use array values to remove keys and then json_encode will turn the arrays into JSON arrays (the square bracket syntax). 您可以使用数组值删除键,然后json_encode将数组转换为JSON数组(方括号语法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM