Using PHP multidimensional arrays to convert MySQL to JSON

前端 未结 4 1819
北荒
北荒 2020-12-12 03:07

Here\'s my table structure.

I\'m trying to convert MySQL to nested JSON, but am having trouble figuring out how to build the multidimensional array in PHP.

T

4条回答
  •  一向
    一向 (楼主)
    2020-12-12 03:51

    I started from Ian Mustafa reply and I figure out to solve the problem of each loop erasing the previous array.

    It's an old thread but I think this could be useful to others so here is my solution, but based on my own data structure (easy to figure out how to adapt it to other structures I think) :

    $usersList_array =array();
    $user_array = array();
    $note_array = array();
    
    $fetch_users = mysqli_query($mysqli, "SELECT ID, Surname, Name FROM tb_Users WHERE Name LIKE 'G%' ORDER BY ID") or die(mysqli_error($mysqli));
    while ($row_users = mysqli_fetch_assoc($fetch_users)) {
        $user_array['id'] = $row_users['ID'];
        $user_array['surnameName'] = $row_users['Surname'].' '.$row_users['Name'];
        $user_array['notes'] = array();
    
        $fetch_notes = mysqli_query($mysqli, "SELECT id, dateIns, type, content FROM tb_Notes WHERE fk_RefTable = 'tb_Users' AND fk_RefID = ".$row_users['ID']."") or die(mysqli_error($mysqli));
        while ($row_notes = mysqli_fetch_assoc($fetch_notes)) {
            $note_array['id']=$row_notes['id'];
            $note_array['dateIns']=$row_notes['dateIns'];
            $note_array['type']=$row_notes['type'];
            $note_array['content']=$row_notes['content'];
            array_push($user_array['notes'],$note_array);
        }
    
        array_push($usersList_array,$user_array);
    }
    
    $jsonData = json_encode($usersList_array, JSON_PRETTY_PRINT);
    
    
    echo $jsonData; 
    

    Resulting JSON :

    [
    {
        "id": "1",
        "surnameName": "Xyz Giorgio",
        "notes": [
            {
                "id": "1",
                "dateIns": "2016-05-01 03:10:45",
                "type": "warning",
                "content": "warning test"
            },
            {
                "id": "2",
                "dateIns": "2016-05-18 20:51:32",
                "type": "error",
                "content": "error test"
            },
            {
                "id": "3",
                "dateIns": "2016-05-18 20:53:00",
                "type": "info",
                "content": "info test"
            }
        ]
    },
    {
        "id": "2",
        "cognomeNome": "Xyz Georg",
        "notes": [
            {
                "id": "4",
                "dateIns": "2016-05-20 14:38:20",
                "type": "warning",
                "content": "georg warning"
            },
            {
                "id": "5",
                "dateIns": "2016-05-20 14:38:20",
                "type": "info",
                "content": "georg info"
            }
        ]
    }
    ]
    

提交回复
热议问题