【问题标题】:Nest JSON from MySQL using PHP使用 PHP 从 MySQL 嵌套 JSON
【发布时间】:2014-11-12 23:33:34
【问题描述】:

我有一个返回下表的 MySQL 查询:

   event_id   name      inv_id    state
       1   At John's   1          0
       1   At John's   2          2
       1   At John's   3          2
       4   Meeting     4          1

我必须通过 PHP 返回一个格式化的 JSON,如下所示:

     [  
       {  
          "id":"1",
          "nombre":"At John's",
          "invitations":[
           { "inv_id":"1", "state":"0" }
           { "inv_id":"2", "state":"2" }
           { "inv_id":"3", "state":"2" }
          ]
       },
       {  
          "id":"4",
          "nombre":"Meeting",
          "invitations":[
           { "inv_id":"4", "state":"1" }
          ]
       }
    ]

基本上,我需要将邀请嵌套在每个事件中。

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    试试这个。

    $rows = [
        ['event_id' => 1, 'name' => 'At John\'s', 'inv_id' => 1, 'state' => 0],
        ['event_id' => 1, 'name' => 'At John\'s', 'inv_id' => 2, 'state' => 2],
        ['event_id' => 1, 'name' => 'At John\'s', 'inv_id' => 3, 'state' => 2],
        ['event_id' => 4, 'name' => 'Meeting', 'inv_id' => 4, 'state' => 1]
    ];
    
    $result = array_reduce($rows, function($result, $row) {
        if (!array_key_exists($row['event_id'], $result)) {
            $result[$row['event_id']] = [
                'id' => $row['event_id'],
                'nombre' => $row['name'],
                'invitations' => []
            ];
        }
    
        $result[$row['event_id']]['invitations'][] = [
            'inv_id' => $row['inv_id'],
            'state' => $row['state']
        ];
    
        return $result;
    }, []);
    
    echo json_encode(array_values($result));
    

    【讨论】:

    • 不得不做一些调整,但效果很好,谢谢!
    猜你喜欢
    • 2018-09-05
    • 2017-07-18
    • 2018-12-29
    • 2019-01-10
    • 2011-02-08
    • 2017-08-25
    • 2015-07-21
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多