我希望将此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
格式相同的输出。
答案 0 :(得分:0)
如果您使用的是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
?>
答案 1 :(得分:0)
您可以使用json_decode函数。 例如;
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo $json;
$array = json_decode($json, true);
print_r($array);
?>
答案 2 :(得分:0)
我找到了你的问题。删除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);
答案 3 :(得分:0)
我了解的是您想将数组编码为所示的json格式。
使用td.fc-other-month {
color: white;
}
代替json_encode($arrResult)
。
json_encode($arrResult, JSON_FORCE_OBJECT)
输出一个对象而不是一个数组。