Skip to content

Instantly share code, notes, and snippets.

@fabiensebban
Created August 28, 2023 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiensebban/ba3d1822c680545ed6f4a6716f8ce61d to your computer and use it in GitHub Desktop.
Save fabiensebban/ba3d1822c680545ed6f4a6716f8ce61d to your computer and use it in GitHub Desktop.
CSV to JSON PHP
/*
File in mydata.csv is formatted as follow:
key1/key2,"value1"
key1/key2/key3,"value2"
key1/key2/key4,"value2"
*/
$file = fopen("mydata.csv", "r");
$data = fgetcsv($file);
$result = [];
var_dump($data);
echo('--------------------------------------');
while(($row = fgetcsv($file)) !== FALSE) {
$hash = [];
var_dump($row[0]);
$result[] = convert_array_in_hash($row[1], explode("/", $row[0]), $hash);
}
echo('*****************************************');
var_dump($result);
var_dump(json_encode($result));
function convert_array_in_hash($value, $array_keys, &$hash, $previous_key = null) {
$key = array_pop($array_keys);
if (count($array_keys) >= 1) {
if($previous_key == null){
$hash[$key] = $value;
} else {
$hash = array($key => $hash);
}
convert_array_in_hash($value, $array_keys, $hash, $key);
} else {
if($previous_key == null){
$hash[] = $key;
} else {
$hash = array($key => $hash);
}
}
//var_dump($hash);
return $hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment