我目前有以下代码,它有一个数组,并将其输出到一个名为'example.json'的JSON文件中.
以下是输出到它的代码:
$x = array(1, 2, 3); //Defining two basic arrays
$y = array(2, 4, 6);
$name = array("Joe", "John", "Johnny");
echo count($x);
$objOne = '["type": "FeatureCollection", "features": [';
file_put_contents("jsonfun.json", json_encode($objOne));
for($i = 0; $i < count($x); $i++)
{
$objTwo = '{ "type": "Feature", "geometry": {"type": "Point", "coordinates": [' . $x[$i] . ', ' . $y[$i] . ']}, "properties": {"name": ' . $name[$i] . '} }]';
file_put_contents("jsonfun.json", json_encode($objTwo), FILE_APPEND);
}
$objThree = '};';
file_put_contents("jsonfun.json", json_encode($objThree), FILE_APPEND);
Run Code Online (Sandbox Code Playgroud)
输出:
"[\"type\": \"FeatureCollection\", \"features\": [""{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [1, 2]}, \"properties\": {\"name\": Joe} }]""{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [2, 4]}, \"properties\": {\"name\": John} }]""{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [3, 6]}, \"properties\": {\"name\": Johnny} }]""};"
Run Code Online (Sandbox Code Playgroud)
你可能已经看到有很多斜线,我不知道它们来自哪里......同样也有一些它们不应该引用的引用;
应该是这样的:
"[type...
Run Code Online (Sandbox Code Playgroud)
我有没有机会删除那些,或者我做错了什么?我尝试过多种方法,比如做JSON_FORCE_OBJECT或者只是以不同的方式键入字符串,但没有任何效果.
原因是你没有使用编码数组/对象json_encode,而是编写一个手动构建的字符串. json_encode对数组,对象或集合中的 JSON进行编码.不是来自字符串.
// This is a string, and will not json_encode properly
$objOne = '["type": "FeatureCollection", "features": [';
file_put_contents("jsonfun.json", json_encode($objOne));
// This is an ARRAY, and will encode properly
$objOne = array( 'type' => 'FeatureCollection',
'features' => array(
'featureOne',
'featureTwo'
)
);
file_put_contents("jsonfun.json", json_encode($objOne));
// Will result in contents of
// {"type":"FeatureCollection","features":["featureOne","featureTwo"]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39 次 |
| 最近记录: |