我希望将此json输出输出到php数组中

问题描述 投票:0回答:4

我希望将此json输出到php数组:

{
    "data": [
        {
            "id": "1",
            "name": "Roger",
            "country": "Switzerland",
            "city": "Basel"
        },
        {
            "id": "2",
            "name": "Rafael",
            "country": "Spain",
            "city": "Madrid"
        },
    ]
}

我正在尝试:

$arrResult = array();
$arrResult['data'] = array();`

while($row = mysqli_fetch_assoc($result)){`
    $id = $row['id'];
    $name = $row['name'];
    $country = $row['country'];

    $arrResult['data'][] = array(
        'id'=> $id,
        'name'=> $name,
        'country'=> $country,
    );
}

echo json_encode($arrResult, JSON_FORCE_OBJECT);

我希望从php数组获得与JSON格式相同的输出。

php arrays json
4个回答
0
投票
这里是如何使用json_decode()的示例

<?php // JSON string $someJSON = '[{"name":"Shriram","gender":"male"},{"name":"Lexa","gender":"female"},{"name":"John Doe","gender":"male"}]'; // Convert JSON string to Array $someArray = json_decode($someJSON, true); print_r($someArray); // Dump all data of the Array echo $someArray[0]["name"]; // Access Array data // Convert JSON string to Object $someObject = json_decode($someJSON); print_r($someObject); // Dump all data of the Object echo $someObject[0]->name; // Access Object data ?>


0
投票
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo $json; $array = json_decode($json, true); print_r($array); ?>

0
投票
<?php $json = '{ "data": [ { "id": "1", "name": "Roger", "country": "Switzerland", "city": "Basel" }, { "id": "2", "name": "Rafael", "country": "Spain", "city": "Madrid" }, <--- THIS IS A PROBLEM ] }'; /* in order for this function to work you need to delete that comma. Because there isn't another list in json so comma should not be there */ $arrResult = json_decode($json, true); print_r($arrResult);

0
投票
[JSON_FORCE_OBJECT输出对象而不是数组。
© www.soinside.com 2019 - 2024. All rights reserved.