使用php转换为json
converting to json using php
我有一个电子表格,我正在转换成json。我能够使用php代码转换。但是我想给数组命名,我该怎么做呢?Php和输出和需要的输出被提到。
Required output
["Name"{"Timestamp":"7'/24'/2015 12:42:41","Name":"ADADSADS","Type":"ASDSD","Place":"ASDSADD","Date":"ASDSD","Time":"ASDSD","Free":"ASDSD","Organizer":"ASDSD","Contact":"ASDSD","Description":"ASDSD","id":0}]
Output from the below code
[{"Timestamp":"7'/24'/2015 12:42:41","Name":"ADADSADS","Type":"ASDSD","Place":"ASDSADD","Date":"ASDSD","Time":"ASDSD","Free":"ASDSD","Organizer":"ASDSD","Contact":"ASDSD","Description":"ASDSD","id":0}]
<?php
/*
* Converts CSV to JSON
* Example uses Google Spreadsheet CSV feed
* csvToArray function I think I found on php.net
*/
header('Content-type: application/json');
// Set your CSV feed
$feed = 'google doc url';
// Arrays we'll use later
$keys = array();
$newArray = array();
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
// Do it
$data = csvToArray($feed, ',');
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
// Add Ids, just in case we want them later
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
// Print it out as JSON
echo json_encode($newArray);
?>
这是无效的json。这么做有什么意义?
substr_replace()替换由开始和分隔的字符串副本(可选)使用replacement.
中给出的字符串指定长度参数。混合substr_replace(混合$string,混合$replacement,混合$replacement$start [, mixed $length])
echo substr_replace(json_encode($newArray), '"Name"', 1, 0);
但如果你指的是{ "Name": <JSON> }
,那么你可以这样做:
echo json_encode(array("Name" => $newArray));
echo json_encode($newArray);
将数据分配给数组键。这样的
$newArray2['name']=$newArray;
echo json_encode($newArray2);
相关文章:
- DOM事件通过JSON转换为java
- 将日期时间从json转换为可读格式
- 如何将JSON转换为HTML下拉菜单
- 将JSON转换为放入Sdcard中的CSV文件
- 将JSON转换为typescript中的字符串数组
- 无法在Angular.js中将JSON转换为数组
- 使用jquery将json转换为数组
- 是否有将基于字符串的JSON转换为Mongoose Schema对象实例的本地功能
- 用D3js将JSON转换为SVG平面图
- 数组json转换为数组json
- 将JSON转换为特定的字符串格式
- 使用AJAX将JSON转换为PHP
- 使用JQuery将JSON转换为数组
- 使用 PHP 将 JSON 转换为 JavaScript
- 将 JavaScript 程序从 JSON 转换为 XML
- 将 JSON 转换为 CSV 格式
- 将 json 转换为 html 表的 JavaScript 不起作用
- 使用 D3 将分层 JSON 转换为 HTML
- 余烬原始 JSON 转换不起作用,但例外
- 如何将JSON转换为角度的HTML