Struggling to convert to json string - php

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

Related

How to make multiple records in array php

From my database i am receaving array, that i`m later sending using Fetch Api to my frontend and display data that was send. It looks like this:
return $stmt->fetchAll(PDO::FETCH_NAMED);
and the given output in JSON is like this:
[
{
"name": [
" name1",
" name2",
" name3"
],
"date": "2022-02-05 12:00:00",
"round": "3",
"coordinate x": "number",
"coordinate y": "number",
"leauge_id": 4
}, etc.
What i want to do is to replace fields coordinate x, coordinate y and insert into this array new field location(based on GoogleGeocodeAPI i will transofrm coordinates into location name) and insert it into this array so i will later be able to display this location.
Here is what i tried to do:
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
foreach ($matches as $match){
$result['nameA'] = $match['name'][0];
$result['nameB'] = $match['name'][1];
$result['nameC'] = $match['name'][2];
$result['date'] = $match['date'];
$result['round'] = $match['round'];
$result['leauge_id'] = $match['leauge_id'];
$result['location']= $this->reverse_geocode($match['coordinate x'],$match['coordinate y']);
}
return $result;
Output from JSON:
{
"nameA": " name",
"nameB": " name",
"nameC": " name",
"date": "2022-02-05 12:00:00",
"round": "29",
"leauge_id": 6,
"location": "location"
}
But it ends up that i`m kinda overwriting the posistion and in the end i am sending only one, the last record. How can i make this work?
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
foreach ($matches as $match){
$result[] = [
'nameA' => $match['name'][0],
'nameB' => $match['name'][1],
'nameC' => $match['name'][2],
'date' => $match['date'],
'round' => $match['round'],
'leauge_id' => $match['leauge_id'],
'location' => $this->reverse_geocode($match['coordinate x'],$match['coordinate y']),
];
}
return $result;
One way to do this is to create a variable $i and use that to key your array...
<?php
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
$i=0;
foreach ($matches as $match){
$result[$i]['nameA'] = $match['name'][0];
$result[$i]['nameB'] = $match['name'][1];
$result[$i]['nameC'] = $match['name'][2];
$result[$i]['date'] = $match['date'];
$result[$i]['round'] = $match['round'];
$result[$i]['leauge_id'] = $match['leauge_id'];
$result[$i]['location']= $this->reverse_geocode($match['coordinate x'],$match['coordinate y']);
$i++;
}
return $result;

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

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

convert series of json objects to single json object

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

How to loop over and access various elements in an array that is both multidimentional and associative? PHP, either JSON or XML

I'm retrieving bibliographic data via an API (zotero.org), and it is similar to the sample at the bottom (just way more convoluted - sample is typed).
I want to retrieve one or more records and display certain values on the page. For example, I would like to loop through each top level record and print the data in a nicely formated citation. Ignoring the proper bib styles for the moment, let's say I want to just print out the following for each record returned:
author1 name, author2 name, article title, publication title, key
This doesn't match the code, because I've clearly been referencing the key value pairs incorrectly and will just make a mess of it.
The following is laid out like the data if I request JSON format, though I can request XML data instead. I'm not picky; I've tried using each with no luck.
[
{
"key": "123456",
"state": 100,
"data": {
"articleTitle": "Wombat coprogenetics: enumerating a common wombat population by microsatellite analysis of faecal DNA",
"authors": [
{
"firstName": "Sam C.",
"lastName": "Smith"
},
{
"firstName": "Maxine P.",
"lastName": "Jones"
}
],
"pubTitle": "Australian Journal of Zoology",
"tags": [
{
"tag": "scary"
},
{
"tag": "secret rulers of the world"
}
]
}
},
{
"key": "001122",
"state": 100,
"data": {
"articleTitle": "WOMBAT and WOMBAT-PK: Bioactivity Databases for Lead and Drug Discovery",
"authors": [
{
"firstName": "Marius",
"lastName": "Damstra"
}
],
"pubTitle": "Chemical Biology: From Small Molecules to Systems Biology",
"tags": [
{
"tag": "Wrong Wombat"
}
]
}
}
]
If there is a mistake in brackets, commas, etc. it is just a typo in my example and not the cause of my issue.
decode your json as array and iterate it as any array as flowing:
$json_decoded= json_decode($json,true);
$tab="\t";
foreach ($json_decoded as $key => $val) {
echo "Article ".$val["key"]."\n" ;
echo $tab."Authors :\n";
foreach ($val["data"]["authors"] as $key => $author){
echo $tab.$tab. ($key+1) ." - ".$author["firstName"]. " ".$author["lastName"]."\n";
}
echo $tab."Article Title: ".$val["data"]["articleTitle"] ."\n";
echo $tab."Publication Title: ".$val["data"]["pubTitle"] ."\n";
echo $tab."Key: ".$val["key"]."\n";
}
run on codepad
and you can use the same method for xml as flowing:
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$json_decoded = json_decode($json,TRUE);
//the rest is same
for xml you can use the SimpleXml's functions
or DOMDocument class
Tip
to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging
Something like this might be a good start for you:
$output = [];
// Loop through each entry
foreach ($data as $row) {
// Get the "data" block
$entry = $row['data'];
// Start your temporary array
$each = [
'article title' => $entry['articleTitle'],
'publication title' => $entry['pubTitle'],
'key' => $row['key']
];
// Get each author's name
foreach ($entry['authors'] as $i => $author) {
$each['author' . ++$i . ' name'] = $author['firstName'] . ' ' . $author['lastName'];
}
// Append it to your output array
$output[] = $each;
}
print_r($output);
Example: https://eval.in/369313
Have you tried to use array_map ?
That would be something like:
$entries = json_decode($json, true);
print_r(array_map(function ($entry) {
return implode(', ', array_map(function ($author) {
return $author['firstName'];
}, $entry['data']['authors'])) . ', ' . $entry['data']['articleTitle'] . ', ' . $entry['key'];
}, $entries));

Categories