如何将此 JSON 输出导入 PHP 数组



我希望这个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格式相同的输出。

我发现了你的问题。删除 json 中的逗号(代码中进行了说明(。

<?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);

如果您使用的是 PHP>= 5.2.0,则可以使用json_decode()

以下是有关如何使用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
?>

您可以使用json_decode函数。 例;

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

我的理解是,您希望将数组编码为所示的 json 格式。

使用json_encode($arrResult)而不是json_encode($arrResult, JSON_FORCE_OBJECT)

JSON_FORCE_OBJECT输出对象而不是数组。

最新更新