convert series of json objects to single json object - php

I have a json file which has series of json arrays
["FIRST_COLUMN", "SECOND_COLUMN", "THIRD_COLUMN" ...]
["John", "Snow", "Game of Thrones", ...]
["Ned", "Snow", "Game of Thrones", ....]
...
but I want one single json object:
[
{"FIRST_COLUMN" : "JOHN", "SECOND_COLUMN" : "SNOW"... } ,
{"FIRST_COLUMN" : "Ned", "SECOND_COLUMN" : "SNOW"... } ,
]
I want to do this in PHP and when I use json_encode I get a json but now in the same format, is there a built in function to do this? if not, how can I get the output ?

You can do something like:
$str = '[["FIRST_COLUMN", "SECOND_COLUMN", "THIRD_COLUMN"],["John", "Snow", "Game of Thrones"],["Ned", "Snow", "Game of Thrones"]]';
//Convert string to array
$arr = json_decode($str, true);
//Remove the first array and store it in a variable
$header = array_shift($arr);
//Loop thru the remaining array
$results = array_map(function ($n) use($header) {
return array_combine($header,$n); //Combine the arrays
}, $arr );
//Convert array to string
echo json_encode($results);
This will result to:
[
{
"FIRST_COLUMN":"John",
"SECOND_COLUMN":"Snow",
"THIRD_COLUMN":"Game of Thrones"
},
{
"FIRST_COLUMN":"Ned",
"SECOND_COLUMN":"Snow",
"THIRD_COLUMN":"Game of Thrones"
}
]
If your original value is string and not a valid json, you can:
$str = '
["FIRST_COLUMN", "SECOND_COLUMN", "THIRD_COLUMN"]
["John", "Snow", "Game of Thrones"]
["Ned", "Snow", "Game of Thrones"]
';
//Convert string to array | Explode by new line and filter.
$arr = array_filter(explode(PHP_EOL, $str),function($e){
return trim($e) !== '';
});
//Remove the first array and store it in a variable
$header = json_decode(array_shift($arr), true);
$results = array_map(function ($n) use($header) {
return array_combine($header,json_decode($n, true)); //Combine the arrays
}, $arr );
echo json_encode($results);

You need array_combine, that's what you need:
$keys = ['firstName', 'lastName', 'age'];
$values = ['John', 'Snow', 27];
$myEntry = array_combine($keys, $values);
// --> ['firstName' => 'John', 'lastName' => 'Snow', 'age' => 27]
just json_decode, loop through the entries, append the keys, json_encode

Related

PHP How to properly merge arrays for following json structure

So i tried a lot of possible codes out but i can't seem to find a proper solution.
First let's start with the the wished array (i will show it in a json format as it's easier to read)
{
"transaction": {
"input": [
{
"address": "a",
"value": 4294967295
},
{
"address": "b",
"value": 51515
}
],
"output": [
{
"address": "aa",
"value": 551
},
{
"address": "bb",
"value": 66564
}
]
}
}
I'm using 2 foreach loops to get data that i wanna put in inputs & outputs
Here's the code im using:
//Get Output Addresses & Value
$tmp_array = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$input = array_merge($input, $tmp_array);
};
$input = array('inputs' => $tmp_array);
$input = json_encode($input);
print_r($input);
That's the code for me getting the data and trying to put it into the array. Now i have a problem, it only adds data from the last iteration of the loop. I'm trying to get a code that gets it in a strucuture like above. Whatever solution gets sent, it should be applicable so i can paste the same code in the other loop that is for the outputs
You are assigning the $input variable after the loop with the value of $tmp_array which will be the value from the last iteration, as you described. To fix this you should initialize the $input array as empty array at the beginning and merge that with the new data:
//Get Output Addresses & Value
$inputs = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$inputs[] = $tmp_array; // push to array
};
$input = json_encode(array('inputs' => $inputs));
print_r($input);

Struggling to convert to json string

I've got a textbox that the user can enter details into it in a csv format. So they would enter something like
user 1,user1#email.com
user 2,user2#email.com
user 3,user3#email.com
The out put of that when I dd(request('users')) is this
user 1, user1#email.com\n
user 2, user2#email.com\n
user 3, user3#email.com
What I would like is to save it in a json format so that it can end up looking like this
[
{
"name": "user 1",
"email": "user1#email.com"
},
{
"name": "user 2",
"email": "user2#email.com"
},
{
"name": "user 3",
"email": "user3#email.com"
}
]
I'm struggling to get it to be like how I would like it. I've tried json_encode(request('users')) but I ended up with
""user 1, user1#email.com\nuser 2, user2#email.com\nuser 3, user3#email.com""
I also tried this
$replace = preg_replace('/\n+/', "\n", trim(request('users')));
$split = explode("\n",$replace);
$json = json_encode($split);
but I got this
"["user 1, user1#email.com","user 2, user2#email.com", "user 3, user3#email.com"]"
The keys name and email you want in your result are not going to appear out of thin air, you need to create them.
Split the data into individual lines, loop over those lines.
Split each line into its two parts.
Create the necessary data structure, introduce the keys you want the data to be stored under at this point.
Encode the whole thing as JSON.
$data = 'user 1,user1#email.com
user 2,user2#email.com
user 3,user3#email.com';
$lines = explode("\n", $data);
$result = [];
foreach($lines as $line) {
$parts = explode(',', $line);
$result[] = ['name' => $parts[0], 'email' => $parts[1]];
}
echo json_encode($result);
You can simply use array_map to map each line to a key-value pair created by using array_combine:
$array = array_map(function($line) {
return array_combine(['name', 'email'], str_getcsv($line));
}, explode("\n", $request('users')));
$json = json_encode($array);
var_dump($json);
The result would be:
string(133) "[{"name":"user 1","email":"user1#email.com"},{"name":"user 2","email":"user2#email.com"},{"name":"user 3","email":"user3#email.com"}]"
Try this
$xx = "user 1, user1#email.com\nuser 2, user2#email.com\nuser 3, user3#email.com";
$xxx = explode("\n",$xx);
$res = [];
foreach($xxx as $y)
{
$new = explode(',',$y);
$res[] = [
'name' => $new[0],
'email' => $new[1]
];
}
echo json_encode($res,true);
Output will be
[
{
"name":"user 1","email":" user1#email.com"
},
{
"name":"user 2","email":" user2#email.com"
},
{
"name":"user 3","email":" user3#email.com"
}
]
Try this
$data = explode("\n", trim(request('users')));
$result = collect($data)->map(function ($row) {
$columns = explode(',', $row);
return [
'name' => $columns[0] ?? null,
'email' => $columns[1] ?? null
];
});

foreach loop in a multidimensional array

Trying to get the a certain parameter in my multidimensional array... I have the following api request:
$responeAPI= ClientCode::request('post', 'responeAPI', $responeAPI,['debug'=>true]);
foreach ($responeAPI["buDetail"] as $key => $value){
$businessUserDet = $value["name"];
}
$storage['enterpriseList'] = $businessUserDet;
}
The array from the API response is like this:
{
"buList": {
"buDetail": [
{
"businessUserId": 2,
"name": "SAMPLENAME_231",
"parentBusinessUserId": 1,
"profileId": 2,
"profileName": "Enterprise"
}
]
},
"resultCode": 0,
"transactionId": "responeAPIs_1577358460"
}
I need to extract the "name" so I can use it for the $options parameter. Right now, my code isn't showing anything.
You can do like this using array_column
$jsonArray = '{"buList":{"buDetail":[{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"},{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"}]},"resultCode":0,"transactionId":"responeAPIs_1577358460"}';
$detais = json_decode($jsonArray, true);
print_r(array_column($detais['buList']['buDetail'], 'name', 'id'));
http://sandbox.onlinephpfunctions.com/code/458592622c78c67771cbf2e54661b9294c91e710
Could you change this line
foreach ($responeAPI["buDetail"] as $key => $value){
to
foreach ($responeAPI["buList"]["buDetail"] as $key => $value){
You can invoke as an object:
$array = '{ "buList": { "buDetail": [{ "businessUserId": 2, "name": "SAMPLENAME_231", "parentBusinessUserId": 1, "profileId": 2, "profileName": "Enterprise" } ] }, "resultCode": 0, "transactionId": "responeAPIs_1577358460" }';
$array = json_decode($array);
//for debug purposes only
echo var_export($array, true);
echo $array->buList->buDetail[0]->name;
Output: SAMPLENAME_231

Using PHP to loop JSON and generate a new format of nested JSON

In PHP, how do I loop through the following JSON Object's date key, if the date value are the same then merge the time:
[
{
date: "27-06-2017",
time: "1430"
},
{
date: "27-06-2017",
time: "1500"
},
{
date: "28-06-2017",
time: "0930"
},
{
date: "28-06-2017",
time: "0915"
}
]
Result should looks like this:
[
{
date: "27-06-2017",
time: [{"1430","1500"}]
}, {
date: "28-06-2017",
time: [{"0930, 0915"}]
}
]
Should I create an empty array, then the looping through the JSON and recreate a new JSON? Is there any better way or any solution to reference?
Thank you!
This solution is a little overhead, but if you are sure that your data is sequential and sorted, you can use array_count_values and array_map:
$count = array_count_values(array_column($array, 'date'));
$times = array_column($array, 'time');
$grouped = array_map(function ($date, $count) use (&$times) {
return [
'date' => $date,
'time' => array_splice($times, 0, $count)
];
}, array_keys($count), $count);
Here is working demo.
Another Idea to do this is
<?php
$string = '[{"date": "27-06-2017","time": "1430"},{"date": "27-06-2017","time": "1500"},{"date": "28-06-2017","time": "0930"},{"date": "28-06-2017","time": "0915"}]';
$arrs = json_decode($string);
$main = array();
$temp = array();
foreach($arrs as $arr){
if(in_array($arr->date,$temp)){
$main[$arr->date]['time'][] = $arr->time;
}else{
$main[$arr->date]['date'] = $arr->date;
$main[$arr->date]['time'][] = $arr->time;
$temp[] = $arr->date;
}
}
echo json_encode($main);
?>
live demo : https://eval.in/787695
Please try this:
$a = [] // Your input array
$op= [];//output array
foreach($a as $key => $val){
$key = $val['date'];
$op[$key][] = $val['time'];
}
$op2 = [];
foreach($op as $key => $val){
$op2[] = ['date' => $key, 'time' => $val];
}
// create the "final" array
$final = [];
// loop the JSON (assigned to $l)
foreach($l as $o) {
// assign $final[{date}] = to be a new object if it doesn't already exist
if(empty($final[$o->date])) {
$final[$o->date] = (object) ['date' => $o->date, 'time' => [$o->time]];
}
// ... otherwise, if it does exist, just append this time to the array
else {
$final[$o->date]->time[] = $o->time;
}
}
// to get you back to a zero-indexed array
$final = array_values($final);
The "final" array is created with date based indexes initially so that you can determine whether they've been set or not to allow you to manipulate the correct "time" arrays.
They're just removed at the end by dropping $final into array_values() to get the zero-indexed array you're after.
json_encode($final) will give you want you want as a JSON:
[{"date":"27-06-2017","time":["1430","1500"]},{"date":"28-06-2017","time":["0930","0915"]}]
Yet another solution :
$d = [];
$dizi = array_map(function ($value) use (&$d) {
if (array_key_exists($value->date, $d)) {
array_push($d[$value->date]['time'], $value->time);
} else {
$d[$value->date] = [
'date' => $value->date,
'time' => [$value->time]
];
}
}, $array);
echo json_encode(array_values($d));

Convert array to JSON in proper format

I'm trying to convert my array to JSON.
My JSON is stored in the database and will later be decoded for permission checking.
Example,
How I want it to be stored in the database:
{ "admin": 1,
"create_posts": 1,
"edit_posts": 1,
"delete_posts": 1 }
How it is being stored now:
{"0":"\"admin\": 1",
"1":"\"create_posts\": 1",
"2":"\"edit_posts\": 1",
"3":"\"delete_posts\": 1"}
My code:
$check_list = $_POST['check_list'];
$list = array();
foreach($check_list as $key) {
$key = '"' . $key .= '": 1';
array_push($list, $key);
}
$json = json_encode($list, JSON_FORCE_OBJECT);
How would I make it so that it stores in the database like I want it to be?
I'm quite new to this, so any hints instead of direct answers is also much appreciated!
UPDATE:
JSON decode and validation:
$permis = json_decode($permissions->permissions, true);
echo ($permis['admin'] == true) ? 'allowed' : 'disallowed';
$arr = [ 'a', 'b', 'c' ];
echo json_encode(
array_combine(
$arr,
array_fill(0, count($arr), 1)
),
JSON_PRETTY_PRINT
);
Output:
{
"a": 1,
"b": 1,
"c": 1
}
http://us3.php.net/manual/en/function.array-combine.php
http://us3.php.net/manual/en/function.array-fill.php
I'm assuming the incoming data looks like this.
$incoming_data = "admin=1&create_posts=1&edit_posts=1&delete_posts=1";
$pairs = parse_str($incoming_data);
so we take the incoming pairs and use the $key as the array index so you don't get the extra array element index.
$permissions = array();
foreach($pairs as $key => $value){
$permissions[$key] = $value;
}
then we encode the new array to get the JSON you're looking for.
print json_encode($permissions);
will print out JSON like this:
{
"admin":"1",
"create_posts":"1",
"edit_posts":"1",
"delete_posts":"1"
}
The main thing to change in your code is this.
foreach($check_list as $key) {
$list[$key] = 1;
}

Categories