使用php转换为json

converting to json using php

本文关键字:json 转换 php 使用      更新时间:2023-09-26

我有一个电子表格,我正在转换成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);