将MySQL查询的结果处理为PHP中所需的JSON结构

时间:2018-10-29 08:26:23

标签: php arrays json

我有此表包含数据: enter image description here 查询的JSON结果:

[{
    "cnt": "1",
    "category_name": "Entertainment",
    "event_name": "Typhoon Sample",
    "year_of_event": "2000"
}, {
    "cnt": "1",
    "category_name": "Heavy Rainfall Warning and Advisory",
    "event_name": "Typhoon Abra",
    "year_of_event": "2015"
}, {
    "cnt": "1",
    "category_name": "Daily Post",
    "event_name": "No Event",
    "year_of_event": " "
}, {
    "cnt": "1",
    "category_name": "Weather Forecast",
    "event_name": "No Event",
    "year_of_event": " "
}, {
    "cnt": "2",
    "category_name": "Actual Docs",
    "event_name": "Holloween",
    "year_of_event": "2018"
}, {
    "cnt": "1",
    "category_name": "Daily Post",
    "event_name": "Holloween",
    "year_of_event": "2018"
}]

我正在尝试像这样转换它:

{
    "category": ["Typhoon Sample 2000", "Typhoon Abra 2015", "No Event ", "Holloween 2018"],
    "series": [{
        "name": "Entertainment",
        "data": ["1",0,0,0]
    }, {
        "name": "Heavy Rainfall Warning and Advisory",
        "data": [0,"1",0,0]
    }, {
        "name": "Daily Post",
        "data": [0,0,"1", "1"]
    }, {
        "name": "Weather Forecast",
        "data": [0,0,"1",0]
    }, {
        "name": "Actual Docs",
        "data": [0,0,0,"2"]
    }]
}

它的作用是,将唯一的event_name分组,然后根据其位置或索引,series属性将包含每个唯一类别的name以及来自查询结果的数据。例如,如果它不具有Entertainment类别的值,则该event_name的值为0

到目前为止我所做的:

while($row = $result_select->fetch_assoc()) {
        $evennt = $row["event_name"]." ".$row["year_of_event"];
        if (!in_array($evennt, $dbdata["category"])){
            $dbdata["category"][]=$evennt;
        }

        $ccat = $row["category_name"];
        $category_names = array_column($dbdata["series"], 'name');  
        if (!in_array($ccat, $category_names)){
            $dbdata["series"][] = array(
                 'name' => $ccat,
                 'data' => []
            );
        }
        print_r ($dbdata["series"]);
        echo '<br/>';
        print_r ($dbdata["category"]);
        echo '<br/>';
        echo 'Current '.$evennt.' --'.$ccat.'<br/>';
        foreach (array_values($dbdata["series"]) as $i => $value)  {

            foreach (array_values($dbdata["category"]) as $ii => $valuee){              

                if(($value["name"] == $ccat) && ($valuee==$evennt ) && ($row["cnt"])){
                    array_push($dbdata["series"][$i]["data"],$row["cnt"]);
                    echo $ii.' : '.$value["name"].' : '.$valuee.' with value '.$row["cnt"].' <br/>';
                }else if (in_array($evennt, $dbdata["category"]) && in_array($ccat, $category_names)){
                    array_push($dbdata["series"][$i]["data"],0);
                    echo $ii.' : '.$value["name"].' : '.$valuee.' without value 0 <br/>';
                }

我坚持使用else语句。 谢谢。

以上代码的结果:

{
    "category": ["Typhoon Sample 2000", "Typhoon Abra 2015", "No Event ", "Holloween 2018"],
    "series": [{
        "name": "Entertainment",
        "data": ["1", 0, 0, 0, 0]
    }, {
        "name": "Heavy Rainfall Warning and Advisory",
        "data": ["1", 0, 0, 0, 0]
    }, {
        "name": "Daily Post",
        "data": ["1", 0, 0, 0, "1"]
    }, {
        "name": "Weather Forecast",
        "data": ["1", 0, 0, 0, 0]
    }, {
        "name": "Actual Docs",
        "data": ["2", 0, 0, 0, 0]
    }]
}

编辑:我的标题可能不正确,实际上不是在转换JSON结构,我的问题是如何将查询结果转换为所需的JSON结构。另外,上面的代码段确实实现了结构或格式,但是data中的值是错误的。

1 个答案:

答案 0 :(得分:1)

我不太确定您的原始逻辑-存在太多缺陷以使其易于修复,因此我做了一个完整的重写:

//prefetch all the DB rows, because we'll be looping them twice
$data2 = $result_select->fetch_all(MYSQLI_ASSOC); 

//next, populate the series and category lists by looking through the data
foreach ($data2 as $row) {
    $evennt = $row["event_name"]." ".$row["year_of_event"];
    if (!in_array($evennt, $dbdata["category"])){
        $dbdata["category"][]=$evennt;
    }

    $ccat = $row["category_name"];
    $category_names = array_column($dbdata["series"], 'name');  
    if (!in_array($ccat, $category_names)){
        $dbdata["series"][] = array(
             'name' => $ccat,
             'data' => []
        );
    }
}

//now process the information to produce the "data" array
foreach ($dbdata["series"] as $serKey => $ser)
{
  foreach ($dbdata["category"] as $catKey => $cat)
  {
    $dbdata["series"][$serKey]["data"][$catKey] = 0; //default value

    foreach ($data2 as $rowKey => $row)
    {
      $rowCat = $row["event_name"]." ".$row["year_of_event"];
      $rowName = $row["category_name"];

      if ($rowName == $ser["name"] && $rowCat == $cat) {
        $dbdata["series"][$serKey]["data"][$catKey] = intval($row["cnt"]);
      }
    }
  }
}

echo json_encode($dbdata);

可以在此处找到演示(使用静态数据代替SQL行数据):http://sandbox.onlinephpfunctions.com/code/6744c95bbbc0043cc015dc10069c7e045154d03c