使用PHP从MySql中嵌套Json

时间:2014-11-12 23:33:35

标签: php mysql json

我有一个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" }
          ]
       }
    ]

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

1 个答案:

答案 0 :(得分: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));