0

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

2
  • 1
    Your Required Output is not valid JSON ... do you know that? Commented Jul 25, 2015 at 8:29
  • Not even close :) ... it should be: '[{"Name":[{"..."}]}]' Commented Jul 25, 2015 at 9:07

2 Answers 2

1

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)); 
Sign up to request clarification or add additional context in comments.

1 Comment

I was just about to comment on your previous comment. Glad that it works for you now.
0

before this line echo json_encode($newArray);

assign the data to an array key.. like this

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.