javascript - 使用php转换为json

标签 javascript php json

我有一个电子表格,我正在将其转换为 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() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.

mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

echo substr_replace(json_encode($newArray), '"Name"', 1, 0);

但如果你的意思是 { "Name": <JSON> }那么你可以这样做:

echo json_encode(array("Name" => $newArray));

关于javascript - 使用php转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31624486/

相关文章:

javascript - 初始化后向 Froala Editor v2 添加选项

javascript - 如何检查html标签是否包含类

javascript - 通过 javascript 将文本和图像的表格 html 导出到 Excel

javascript - jQuery-UI 对话框仅显示 for 循环的最后一次迭代

用 return 结束函数时加载 JSON 时出现 Python 错误

android - JSON 的问题

javascript - 正确使用 Javascript DOM

javascript - 带 D3 正交的圆形剪辑和投影

javascript - jQuery :not (:contains) not working with ACF select field/<select><option> tag/

php - 在 FullCalendar 4 中显示我的数据库中的事件