I am using PHP and converting the JSON data into the CSV format and later on read the same CSV file for further processing.
Below is my code that converts the JSON data in to the CSV format.
function LoadDataFromFile($file)
{
$json = file_get_contents($file);
$array = json_decode($json, true);
$f = fopen('out.csv', 'w');
$firstLineKeys = false;
$keys = array();
//first collect keys
foreach($array as $line){
foreach($line as $key => $value){
if(!in_array($key, $keys))
$keys[] = $key;
}
}
$keyString = implode(",", $keys);
fwrite($f, "$keyString\n");
foreach ($array as $line)
{
$outputArray = array();
foreach($keys as $key){
if(array_key_exists($key, $line)){
$outputArray[] = str_replace(',', '', $line[$key]);;
} else {
$outputArray[] = "";
}
}
$outputString = implode(",", $outputArray);
fwrite($f, "$outputString\n");
}
fclose($f);
}
As we can see that, i am writing data into the "out.csv" file, and later on i am reading same CSV file and assign the value/ full contents of the same file line by line to $array variable, as shown below.
$array = explode("\n", file_get_contents('out.csv'));
Now, I want to directly assign the value of csv contents into the $array variable with out using the intermediate "out.csv" file.
Wondering what data structure should i use while converting JSON data to CSV format, and possible code changes required for "LoadDataFromFile" method?
If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?
Instead of:
fwrite($f, "$outputString\n");
you can put:
$csv .= $outputString;
And finish it with:
$array = explode("\n", $csv);
This question already has answers here:
Parsing JSON in PHP
(2 answers)
Closed 5 years ago.
I got a JSON from a web site in the raw format:
{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}, ... }
How do I get the A_B and A_C??? I do not know what A_B and A_C could be.
Try the following.
$json = file_get_contents("your json data");
$arr = json_decode($json, true);
foreach ($arr as $key=>$val) {
var_dump($key);
}
Finally, var_dump($key) displays A_B and A_C.
Suppose you have that raw json in some variable, say $yourJson
First, parse your json. $parsedJson = json_decode($yourJson, true)
Then run a foreach loop and stop after 2 iterations, You will (hopefully) get the right key-value pair.
$i = 0;
$extractedValues = [];
foreach ($parsedJson as $key => $value) {
$extractedValues[$key] = $value; $i++;
if ($i === 2) {
break;
}
}
Now, $extractedValues contains only two elements found from the first two iterations.
$data = json_decode("Your json variable");
foreach($data as $value){
echo $value; // here you receive your desire value.
}
Try this:
$json = '{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}}';
$dataArray = json_decode($json, true);
$arrayKeys = array_keys($dataArray); // in your case A_B and A_C
and if you want to get their values then:
foreach($dataArray as $data) {
foreach($data as $key => $value) {
echo $key . ": " . $value . PHP_EOL;
}
}
var $jsonObj = json_decode('{"A_B":{"id":7,"last":"0.00000038"}}')
print $jsonObj->{'A_B'}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have this json held in a variable that I am trying to convert to a string?
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
What I want as my end result is something that looks like this:
$json_object1 = '1,2,3,4,5,6,7,8,9,10,11';
$json_object2 = '125,126,127,128,129,130,131,132,133,134,135';
Is there a way we can modify the implode(",",$json_object) function to achieve this?
Another question:
Any idea how we might put this
{"26":"Child - 1500.00","28":"Foreigner - 4000.00","27":"Resident - 3000.00"}
To a list like
26 : Child - 1500.00
27: Resident - 3000.00
28: Foreigner - 4000.00
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$json = json_decode($json_object);
echo implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $p;} }, $json));
echo "<br>";
echo implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $v;} }, $json));
See https://3v4l.org/p3p45
Try this:
<?php
$jsonString = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$decoded = json_decode($jsonString, true);
$keys = [];
$values = [];
foreach($decoded as $item) {
foreach($item as $key => $value) {
$keys[] = $key;
$values[] = $value;
}
}
$resultStringKeys = implode(",", $keys);
$resultStringValues = implode(",", $values);
var_dump($resultStringKeys, $resultStringValues);
The output:
string(43) "125,126,127,128,129,130,131,132,133,134,135"
string(23) "1,2,3,4,5,6,7,8,9,10,11"
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$arr1 = []; $arr2=[];
$jsonobj = json_decode($json_object);
foreach ($jsonobj as $val){
$Arrval = (array) $val;
foreach ($Arrval as $k=>$v){
$arr1[]=$k;
$arr2[]=$v;
}
}
$json_object1 = implode(",",$arr1);
$json_object2 = implode(",",$arr2);
Out put is
125,126,127,128,129,130,131,132,133,134,135
1,2,3,4,5,6,7,8,9,10,11
Another possible solution (not the best if the size of your JSON input is measured in MBs but good enough for several KBs of input):
$input = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
// Decode the JSON into arrays; TRUE as the second argument requires arrays, not objects
$data = json_decode($input, TRUE);
// Run through the list, extract the data into a new list
$output = array_reduce(
$data,
function(array $carry, array $item) {
// Put the keys and values of $item into the corresponding lists on $carry
$carry['keys'] = array_merge($carry['keys'], array_keys($item));
$carry['vals'] = array_merge($carry['vals'], array_values($item));
return $carry;
},
// Start with empty lists of keys and values
array('keys' => array(), 'vals' => array())
);
// That's all; $output['keys'] contains the keys, $output['values'] contains the values.
echo('Keys: '. implode(',', $output['keys'])."\n");
echo('Values: '.implode(',', $output['vals'])."\n");
You can achieve like this,
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$key_arr = array();
$val_arr = array();
$json_arr = json_decode($json_object);
foreach($json_arr as $val)
{
foreach($val as $key => $value)
{
$key_arr[] = $key;
$val_arr[] = $value;
}
}
$resultStringKeys = implode(",", $key_arr);
$resultStringValues = implode(",", $val_arr);
And echo your $resultStringKeys and $resultStringValues and you will get your output.
first convert json data to php array then store all key and value in different array then implode it
<?php
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$array_data = json_decode($json_object, true);
foreach($array_data as $data) {
foreach($data as $key => $value) {
$array_key[] = $key;
$array_value[] = $value;
}
}
$final_key = implode(",", $array_key);
$final_value = implode(",", $array_value);
echo $final_key;
echo "<br>";
echo $final_value;
then output is :
125,126,127,128,129,130,131,132,133,134,135
1,2,3,4,5,6,7,8,9,10,11
I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}