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;
Related
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);
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
];
});
I have a PHP code like:
while ($row2 = mysqli_fetch_assoc($check2)) {
// $leadarray[] = $row2;
$service_id[$i] = $row2['service_id'];
$row1['service_id'][$i] = $service_id[$i];
$service_name[$i] = $row2['service_name'];
$row1['service_name'][$i] = $service_name[$i];
$i++;
}
$leadarray[] = $row1;
$trimmed1['leaddetails'] = str_replace('\r\n', '', $leadarray);
echo json_encode($trimmed1);
getting output like
{
"leaddetails": [
{
"service_id": [
"7",
"2"
],
"service_name": [
"Past Control Services",
"Civil Finishing"
],
}
]
}
I want output like:
"service_id": [
1: "7",
2: "2"
],
"service_name": [
1: "Past Control Services",
2: "Civil Finishing"
],
or
[
"service_id": "7",
"service_name": "Past Control Services",
"service_id": "2",
"service_name": "Civil Finishing",
]
$trimmed1 is considered an object when passing it to json_encode (associative array in PHP) because you explicitly give it a key (considered an object property in JSON):
$trimmed1 = [];
$trimmed1['leaddetails'] = 'foobar';
This will result in json_encode encoding $trimmed1 into an object:
{
"leaddetails": "foobar"
}
To get your desired result, have $trimmed1 be considered an ARRAY when passed to json_encode.
$trimmed1[] = str_replace('\r\n', '', $leadarray); // push instead of assign
second option is not posible
you can make like this
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
using class for make like that
class Data{
$service_id;
$service_name;
}
$obj = new Array();
while ($row2 = mysqli_fetch_assoc($check2)){
$data = new Data();
$data->service_id = $row2['service_id'];
$data->service_name = $row2['service_name'];
array_push($obj, $data);
}
echo json_encode($obj);
Create the 2-dimensional array first. Then push onto the nested arrays during the loop.
$result = ["service_id" => [], "service_name" = []];
while ($row2 = mysqli_fetch_assoc($check2)) {
$result["service_id"][] = $row["service_id"];
$result["service_name"][] = $row["service_name"];
}
echo json_encode($result);
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));
I have a json file with data like this (this is a partial view of the file to show structure):
{
"state": {
"ALABAMA": {
"ZOLD": [ "101", "102" ],
"ZNEW": [ "11", "12" ]
},
"ALASKA": {
"ZOLD": [ "5001", "5002", "5003", "5004", "5005", "5006", "5007", "5008", "5009", "5010"],
"ZNEW": [ "21", "22", "23", "24", "25", "26", "27", "28", "29", "20"]
}
}
}
What I want to do is search through it to find a value in the ZOLD field = $OLD, then return the value of the corresponding ZNEW array. I've tried going in with foreach and can get the arrays to echo out, but I'm not sure of what the value will be. Here's the code I have:
function translateZone($OLD)
{
$OLD = "5010"; //for testing purposes a constant but will be variable
$zStr = file_get_contents('getnew.json');
$zJson = json_decode($zStr,true);
foreach($zJson as $key=> $jsons)
{
foreach($jsons as $key=>$values)
{
foreach($values as $key=>$vals)
{
$counter=0;
foreach($vals as $key=>$vls)
{
$counter ++;
echo var_dump($vls);//I can see the values,but now what?
if ($vls == $OLD)
{
$zTemp = Help here -some array value of counter??
}
}
}
return $zTemp;
}
}
I've searched through a bunch of other questions but haven't found something close enough to help with the problem.
Additional information: I may or may not know the "state" string (i.e. "Alaska") but I may want to return this information as well based on the found value.
Thanks for the help.
Instead of trying to loop through ZOLD, you could use array_search (assuming that the $OLD value can only appear once in the data). This function will either return a number for the index of the value you search for or false if it cannot find it:
$index = array_search($OLD,$values['ZOLD']);
if ($index !== FALSE) {
$zTemp = $values['ZNEW'][$index];
}
This would replace your two innermost for loop (as you need the other loops to get down to this level) and iterate through each state. At this point as well, $key would be defined to your state name.
Here is another way to complete your task, this one with array_map function:
$jsonArray = json_decode($your_file_content, true);
$oldVal = "5005";
$result = [];
foreach( $jsonArray["state"] as $k => $v ) {
/**
* Here we're building an array or pairs ZOLD => ZNEW values
*/
$pairs = array_map(function($o, $n) {
return [ $o => $n ];
}, $v["ZOLD"], $v["ZNEW"]);
/**
* Filling up the result
*/
foreach( $pairs as $p )
if( isset($p[$oldVal]) )
$result[] = [
"state" => $k,
"ZNEW" => $p[$oldVal]
];
}
var_dump($result);
$result dump will contains a list or assoc arrays with "state" and "ZNEW" keys, if the corresponding ZNEW values will be found