PHP JSON Group的值相同

时间:2015-06-13 06:34:55

标签: php mysql json

我正在思考如何使用相同值的对象对数组进行分组。

我有来自MySQL查询的结果:

| Id |    Name     |     Date     |  Value  |
|----|-------------|--------------|---------|
| 1  |    Jeff     |  2014-12-01  |    5    |          
| 1  |    Jeff     |  2015-12-01  |    8    | 
| 2  |    David    |  2014-12-01  |    7    |      
| 2  |    David    |  2015-12-01  |    6    |   

如果我使用echo json_encode():


$json = array();

    while($row = mysqli_fetch_assoc($result)) {             
        $bus = [
        'id' => $row["id"],
        'name' => $row["name"],
        'date' => $row["date"],
        'value' => $row["value"]
        ];

        array_push($json, $bus);    
        }

echo json_encode($json);

结果是:

[

    {
        "Id": "1",
        "Name": "Jeff",
        "Date": "2014-12-01",
        "Value": "5"
    },
    {
        "Id": "1",
        "Name": "Jeff",
        "Date": "2015-12-01",
        "Value": "8"
    },
    {
        "Id": "2",
        "Name": "David",
        "Date": "2014-12-01",
        "Value": "7"
    },
    {
        "Id": "2",
        "Name": "David",
        "Date": "2015-12-01",
        "Value": "6"
    }


]

但是,有可能用php获取这样的json数组吗?

[

    {
        "Id": "1",
        "Name": "Jeff",
        "Values":[
               {
                 "2014-12-01": "5",
                 "2015-12-01": "8"
               }
                  ]
    },
    {
        "Id": "2",
        "Name": "David",
        "Values":[
               {
                 "2014-12-01": "7",
                 "2015-12-01": "6"
               }
                  ]
    }

]

2 个答案:

答案 0 :(得分:0)

试试这个

<?php

$json = array();

while ($row = mysqli_fetch_assoc($result)) {

    if (is_array($json)) {
        foreach ($json as $key => $val) {
            if ($val['Id'] == $row["id"]) {
                $json[$key]['date'][] = $row["date"];
                continue;
            }
        }
    }
    $json[] = array(
        'id' => $row["id"],
        'name' => $row["name"],
        'date' => array($row["date"]),
        'value' => $row["value"]);
}

echo json_encode($json);

答案 1 :(得分:0)

我不知道是否可以获取您想要的数据只需使用sql。

通常,我会用php做这个工作

<?php
$json = array();

foreach ($array as $idx => $data) {
    //Id is not exists in json,create new data 
    if( !array_key_exists($data['Id'], $json) ){//Id is unique in db,use Id for index ,you can find it easily
        $json[$data['Id']]=array(
            'Id'  =>$data['Id'],
            'Name'=>$data['Name'],
            'Value'=>array(
                    $data['Date']=>$data['Value']
                )
        );
        continue;
    }

    //Id is exists in json, append value
    $json[$data['Id']]['Value'][$data['Date']] =$data['Value'];
}
$json = json_encode($json);

希望我能帮到你