Vikhyath Maiya
Vikhyath Maiya

Reputation: 3192

converting to json using php

I hav a spreadsheet which i am converting into a json.I am able to convert using the php code.But i wanto name the array .How can i do this ..Please help..Php and output and required output is mentioned.

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);

?>

Upvotes: 0

Views: 41

Answers (2)

Sebastian Nette
Sebastian Nette

Reputation: 7812

That is not valid json. What would be the point of doing this?

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);

But if you mean { "Name": <JSON> } then you could do:

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

Upvotes: 1

captain_a
captain_a

Reputation: 3287

before this line echo json_encode($newArray);

assign the data to an array key.. like this

$newArray2['name']=$newArray;
echo json_encode($newArray2);

Upvotes: 0

Related Questions