How to add to json array in .json file with php? - php
I have this json array in json file
[["a","b","c","d"],["3","2","25","25"],["4","48","20","20"],["3","1","22","22"],["5","4","31","31"],["5","3","33","33"],["5","6","43","43"],["5","8","45","45"],["5","5","42","42"],["5","11","37","37"],["5","7","40","40"],["5","10","36","36"],["1","35","40","40"],["2","22","38","38"],["2","23","35","35"],["1","31","34","34"],["2","19","43","43"],["2","17","35","35"],["3","14","20","20"],["3","15","17","17"],["3","13","16","16"],["2","20","36","36"],["1","39","28","28"],["3","26","20","20"],["4","46","20","20"],["1","36","32","32"],["1","37","21","21"],["3","9","5","5"],["3","12","23","23"],["3","18","21","21"],["3","16","22","22"],["3","21","15","15"],["4","34","6","6"],["1","33","29","29"],["1","32","24","24"],["1","30","30","30"],["3","24","27","27"],["3","27","23","23"],["3","25","23","23"],["3","28","6","6"],["3","29","18","18"],["4","47","19","19"],["4","51","6","6"],["4","50","4","4"],["1","49","26","26"],["1","40","41","41"],["1","41","43","43"],["4","43","2","2"],["4","44","1","1"],["1","38","44","44"],["1","45","37","37"],["1","42","39","39"],["4","61","3","3"],["4","60","7","7"],["4","57","10","10"],["4","58","14","14"],["4","56","8","8"],["4","54","12","12"],["4","59","9","9"],["4","55","10","10"],["4","53","11","11"],["4","52","13","13"]]
I need to add another array to the above json array,
that is
[["e"],["45"
],["37"],["40"],["57"],["61"],["85"],["96"],["79"],["71"],["77"],["68"],["77"],["73"],["65"],["64"],
["85"],["65"],["37"],["31"],["30"],["68"],["49"],["37"],["37"],["60"],["39"],["21"],["42"],["39"],["40"
],["28"],["22"],["51"],["43"],["55"],["48"],["42"],["42"],["22"],["34"],["35"],["22"],["18"],["47"],
["78"],["85"],["104"],["100"],["92"],["71"],["74"],["140"],["222"],["248"],["276"],["229"],["259"],["233"
],["248"],["250"],["268"]]
I need the output like this in Array
[["a,b,c,d,e"],["3","2","25","25","45"]]
I'm not able to do it in array_push, array_merge. Can any help me ?
Thanks in advance ...
You should have get the json string in a php variable. then:
$array1 = json_decode($json_string1, true);// not needed if already you have an array
$array2 = json_decode($json_string2, true);
$merged = array();
foreach( $array1 as $key => $value ){
if(array_key_exists($key, $array2)){
$merged[] = array_merge($value, $array2[$key]);
}else{
$merged[] = $value ;
}
}
Related
How to prevent overriding in array?
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; }
how to remove empty array value with key in php?
I am getting an array similar to the following one. {"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]} If form data values are null, I want to replace that key's value with the value of the next key. Like above, after value 5, I have null values. It needs to be like this: "final_data":["1","2","4","5","fill this with 6","remove this"] "final_data":["1","2","4","5","6"] like this I tried array_filter(), but it didn't help.
If the response is in json format then ... $json = '{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}'; $array = json_decode($json, TRUE); foreach($array as $index => $a) { $array[$index] = array_filter($a); } print_r($array); https://eval.in/866379 Update: foreach($array as $index => $a) { $array[$index] = array_value(array_filter($a)); } https://eval.in/866522
try following code, foreach($myarray as $key=>$value) { if(is_null($value) || $value == '') unset($myarray[$key]); }
Try this array_filter() with array_map() and array_values() <?php $array = array("form_data" => array("1","2","4","5","","6"), "final_data" => array("1","2","4","5","","6")); function filterMe($paraArr){ return array_values(array_filter($paraArr)); } $array = array_map("filterMe",$array); echo "<pre>"; print_r($array); check the output here https://eval.in/866401
Decoding json in array , editing array and encoding in json - PHP
I am newbee in php and trying to get json in array and wanna change key in that json below is my code : $json = json_decode(file_get_contents('all_json_files/jobs.json'), true); foreach ($json as $key=>$row){ foreach ( $row as $key=>$row){ foreach ( $row as $key=>$row){ foreach ($row as $key=>$row){ if(strcmp($key,"security_block")==0) { foreach ($row as $k=>$r){ if(strcmp($k,"job_payload_hash")==0) { $row[$k]['job_payload_hash']=$base64String; print_r($row); } } } } } } } print_r($json); Issue is print_r($row); is updating properly but print_r($json); does not print the updated string .
If the key could appear anywhere, the answer is pretty simple: function update_hash(&$item, $key, $base64String) { if ($key == "job_payload_hash") { $item = $base64String; } } array_walk_recursive($json, 'update_hash', 'something'); Update The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach: foreach (array_keys($json['jobs']) as $jobId) { $json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something'; }
You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work.. You can use recursive function lik answer of #Ja͢ck .
this is because you have to save not in variables you defined after => in a foreach. You have to store this in format: $json[0][0] ... = $base64String; OR You have to add a new array like $result = array() before you write the foreach and then store it in $result.
Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string. Also, use array_key_exists() rather than comparing array key strings. $array = json_decode($json); if(array_key_exists("job_payload_hash", $array){ $array["job_payload_hash"] = base64encode($var); } $json = json_encode($array);
JSON and Arrays mixed up (in PHP)
This is what I get from my SQL selection. The data is correct, now I'd like to echo it by foreach. Array ( [0] => stdClass Object ( [sql_column] => [{"1":"value1", "2":"value2", "3":"value3"}] ) ) What I've tried (and which didn't work) was: $obj = json_decode($arr); foreach($obj as $data){ echo $data->sql_column->1; //this should echo "value1", but it doesn't } Does anyone see my mistake? Thanks in advance!
If $arr is the array you posted then you can't json_decode it since it's an array and not a JSON string. //First you need to get the string $json = $arr[0]->sql_column; //Then decode $data = json_decode($json); //Then loop foreach($data as $key => $value){ echo "$key = $value \n"; }
Your json seems to be complicated (double dimensional array), but you can fetch values from it in this manner: foreach($arr as $data){ $json = json_decode($data->sql_column); $temp = (array)$json[0]; foreach($temp as $k=>$v){ print($v."<br/>"); } } I hope you get an idea... I used foreach for $arr to cover multi values, you can omit that if you want: $data=$arr[0]; $json = json_decode($data->sql_column); $temp = (array)$json[0]; foreach($temp as $k=>$v){ print($v."<br/>"); }
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; }