How to prevent overriding in array? - php

I'm trying to add all the keys of different json available in a file to an array. What I did for the moment is this:
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($jsonData as $line)
{
//Convert the json in an associative array
$array = json_decode($line, true);
//Iterate through the json keys
foreach($array as $k => $val)
{
$json[$k] = $val;
}
}
the json file is like this:
{"Timestamp":"2018-06-14T10:46:52.3326036+02:00","Level":"Error","MessageTemplate":"System.Exception"}
{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"}
I'll get this:
{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"}
because the $json[$k] override I guess the previous array, but $k is a new json so why the index of the array is replaced?
Thanks in advance for any help.

may be this one is your expected output.
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($jsonData as $line)
{
//Convert the json in an associative array
$array = json_decode($line, true);
$temp = [];
//Iterate through the json keys
foreach($array as $k => $val)
{
$temp[$k] = $val;
}
$json[] = $temp;
}

change this line
foreach($array as $k => $val)
{
$json[$k] = $val;
}
to
foreach($array as $k => $val)
{
$json[][$k] = $val;
}

Well you're overwriting keys with the same names, so there's really nothing surprising in your output.
You probably meant to do this:
foreach($jsonData as $line) {
$tmp = []; //<-- set up a new array just for this iteration
$array = json_decode($line, true);
foreach($array as $k => $val) $tmp[$k] = $val;
$json[] = $tmp; //<-- log the array in the master $json array
}

//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Convert the json in an associative array
$array = json_decode($jsonData, true);
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($array as $k => $val)
{
$json[][$k] = $val;
}

Related

How to convert JSON data to CSV format on the fly with out using csv file

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

Retrieve first element of JSON with php [duplicate]

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'}

Parse JSON data from multiple options

I'm trying to parse JSON data in the format [{code:SE rate:1.294},{code:UK rate:2.353}] from this page:
http://www.mycurrency.net/service/rates
I have implemented an IP reader that detects the users location in a 2 letter country code. I want to pluck the correct data from that link with 'code' and return the value 'rate'. I was thinking I might have to do a foreach loop to iterate through all the countries?
This is my code, I hope this is what are you looking for.
First I create a new array $output to make it more easy to search
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
After that we use a function to search value in array and returning the key. I got it from here
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
and then I run the function with the first parameter as country code to get the keys of specific country code.
$find = searchForRate("BT", $output);
And then echo the rates from our $output array by key in $find variable
echo 'RATE = '.$output[$find]['rate'];
This is the complete codes
<?php
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
$find = searchForRate("BT", $output);
echo 'RATE = '.$output[$find]['rate'];
Example output:
RATE = 64.13

How do I implode a json object to a string in php? [closed]

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

PHP Can't get the right format for array

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

Categories