This question already has an answer here:
How to store column data as comma separated values when finding duplicate values in another column? [duplicate]
(1 answer)
Closed 4 years ago.
I am working with a JSON dataset provided via CSV file from my client. I have processed the CSV into a JSON format.
I have the following result (dataset reduced from 1304 to 2 for readability)
"1": {
"title": "Abercarn RFC",
"address": "High Street, Abercarn, Newport, Gwent",
"postcode": "NP11 5GQ",
"category": "Club",
"website": "http://abercarn.rfc.wales",
},
"2": {
"title": "Abercarn RFC",
"address": "High Street, Abercarn, Newport, Gwent",
"postcode": "NP11 5GQ",
"category": "Seniors",
"website": "http://abercarn.rfc.wales",
}
I want to be able to loop through my array (pre-json_encode($array)) and merge these objects but preserve both the category values into a CSV list, so the ideal output in this case will be
"category": "Club, Seniors"
I am happy to simply merge all the other fields as they are consistently the same across the data set.
You can do it with simple loop (I used the title to define similarity between element but you can change that):
$arr = array(["title" => "Abercarn RFC", "category"=> "Club"], ["title" => "other title", "category"=> "BlaBla"], ["title" => "Abercarn RFC", "category"=> "Seniors"]);
$res = array();
foreach($arr as $e) {
if (isset($res[$e["title"]]))
$res[$e["title"]]["category"] .= ", " . $e["category"];
else $res[$e["title"]] = $e;
}
If you want to remove the array key you can use array_values.
$res will be your desire output.
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
I'm using Laravel. I have JSON returned from Database.
I would like to get key names like "id / name / email / revision" from following JSON.
{
"id": "000",
"records": [
{
"id": 23,
"name": "hoge",
"email": "Hoge#alk.jp",
"revision": 0
},
{
"id": 24,
"name": "zaku",
"email": "zaku#alk.jp",
"revision": 0
},
]
}
Please let me know how to get key names.
Thank you.
You should get the keys with collection get key by code following:
collect($data->records)->keys();
This will return
id
name
email
revision
More detail you can check here: https://laravel.com/docs/8.x/collections#method-keys
Use json_decode to convert it to an array:
$array = josn_decode($jsonVariable, true);
Then use foreach:
foreach($array['records'][0] as $key => $value){
$keys[] = $key;
}
or array_keys:
array_keys($array['records']);
or collect to get keys:
$keys = collect($array['records'])->keys();
I'm running MySQL 8 in a dev environment, learning as I go. I'm running a very simple PHP 7 RestAPI.
Here is how I'm executing a simply MySQL lookup:
$blockStmt = 'SELECT JSON_ARRAY(JSON_OBJECT("value", titleId, "title", titleDesc))
FROM titleTable ORDER BY titleDesc';
$preppedQuery = $db->query($blockStmt);
$blockResult = mysqli_fetch_all($preppedQuery);
print_r(json_encode($blockResult));
Here is how the result set is being returned by the print_r
[
[{"title": "Title 1", "value": "title1"}],
[{"title": "Title 2", "value": "title2"}],
[{"title": "Title 3", "value": "title3"}]
]
Here is how I WANT the results to be formatted:
[
{"title": "Title 1", "value": "title1"},
{"title": "Title 2", "value": "title2"},
{"title": "Title 3", "value": "title3"}
]
I've been working with the various JSON commands and can't seem to keep MySQL from encapsulating each result row as an array containing a single JSON, instead of just returning it as a JSON only.
Any tips? Thanks so much in advance!
Don't use the JSON functions, just return the columns that you want. mysqli_fetch_all() will then return associative arrays, and json_encode() will convert them to JSON.
$blockStmt = 'SELECT titleId AS value, titleDesc AS title
FROM titleTable ORDER BY titleDesc';
$preppedQuery = $db->query($blockStmt);
$blockResult = mysqli_fetch_all($preppedQuery, MYSQLI_ASSOC);
print_r(json_encode($blockResult));
This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 3 years ago.
Assume I have this array list in php
[
{
"id": "1",
"name": "test1",
},
{
"id": "2",
"name": "test2",
},
]
How can I easily return the id that have name=test1?
Try using array_search(). First, get the place of the id, name pair and get the content of the id field next.
//Get the key of the 'id, name' pair
$key = array_search('test2', array_column($input, 'name'));
//Get the id beloning to the name
$id = $input[$key]->id;
A working example here.
I assume you have multilevel array, so you do using foreach function as below.
$x= array(array('id'=>'1','name'=>'test1'),array('id'=>'2','name'=>'test2'));
foreach($x as $value){
if($value['id'] =="1" && $value['name'] == "test1"){
// Do your stuff
}
}
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 7 years ago.
I'm new to PHP and I'm trying to use it to filter information from the New York Times' article search API. I'm still struggling to figure out how I can pull out the "web-url" and "snippet" from the JSON response even after looking through this similar question. I'm using json_decode to turn the response into an associative array. Here's my code
$data = file_get_contents($queryURL);
$jsondata = json_decode($data, true);
if (count($jsondata) != 0)
{
foreach($jsondata['response']as $key => $value)
{
echo "Key: " . $key . " Value: " . $value . " <br>";
}
}
This only prints out the words "array", "ok" and "copyright".
Here's a sample of the json:
"response": {
"meta": {
"hits": 25,
"time": 332,
"offset": 0
},
"docs": [
{
"web_url": "http://thecaucus.blogs.nytimes.com/2012/01/01/virginia-attorney-general-backs-off-ballot-proposal/",
"snippet": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"lead_paragraph": "DES MOINES -- Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"abstract": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"print_page": null,
"blog": [ ],
"source": "The New York Times",
"multimedia": [ ],
"headline": {
"main": "Virginia Attorney General Backs Off Ballot Proposal",
"kicker": "The Caucus"
},
Try this. You need to loop through each of the docs
foreach ($jsondata['response']['docs'] as $doc) {
echo "web_url: " . $doc['web_url'] . " snippet: " . $doc['snippet'];
}
When you are looping through $jsondata['response']
then when your $key is meta (Similarly for other keys as well like docs etc) its $value is an array i.e
array(
"hits"=> 25,
"time"=> 332,
"offset"=> 0
)
So when you are trying to echo this $value it prints array as its a property of echo in php to print arrays as string "array".
I hope this makes clear what you are doing wrong!!!
You might need to do something like this
foreach($jsondata['response']as $key => $value)
{
// check if $jsondata['response'][$key] is an array using is_array()
// handle as per array
}
Learn about is_array
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 10 months ago.
Let's say I have this JSON:
{
"achievement": [
{
"title": "Ready for Work",
"description": "Sign up and get validated",
"xp": 50,
"difficulty": 1,
"level_req": 1
},
{
"title": "All Around Submitter",
"description": "Get one piece of textual content approved in all five areas.",
"xp": 500,
"difficulty": 2,
"level_req": 1
}
}
and I am trying this thru PHP:
$string = file_get_contents("achievements.json");
$json_a=json_decode($string,true);
$getit = $json_a->achievement['title'][1];
I'm trying to get the first "id" of the achievement.. which would be READY FOR WORK.
How do I fix this?
When you set the second parameter of json_decode to true, it will return an array.
$json_a=json_decode($string,true);
returns an array.
$getit = $json_a['achievement'][1]['title'];