我目前有以下代码,它有一个数组,并将其输出到名为' 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);
输出:
"[\"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} }]""};"
你可能已经看到有很多斜线,我不知道它们来自哪里......同样也有几个引用它们不应该是;
应该是这样的:
"[type...
我有可能删除那些,或者我做错了吗?我尝试过多种方法,例如执行JSON_FORCE_OBJECT
或只是以不同的方式键入字符串,但没有任何效果。
答案 0 :(得分:5)
原因是您没有使用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"]}