I want to use following JSON query in PHP:
{
"match_phrase" : {
"message" : {
"query" : "this is a test",
"analyzer" : "my_analyzer"
}
}
}
Now I have PHP code:
$params['body']['query']['match_phrase'] = array(
"name" => $query
);
$this->result = $this->client->search($params);
How I can convert JSON query in PHP array query according to elasticsearch php?
One way of doing it is a like this:
$params['body']['query']['match_phrase'] = array(
"message" => array(
"query" => $query,
"analyzer" => "my_analyzer"
)
);
$this->result = $this->client->search($params);
Another way which is probably better when working with Elasticsearch is to use the json_decode function. That way you can easily write your queries in JSON using the
query DSL without the trouble of constructing it via associative arrays.
$json = '{
"match_phrase" : {
"message" : {
"query" : "' . $query . '",
"analyzer" : "my_analyzer"
}
}
}';
$params['body']['query'] = json_decode($json);
$this->result = $this->client->search($params);
Related
I use PHP Guzzle to fetch API and want to merge JSON arrays.
The API URL is https://example.com/api/v2/content/?categories=1234,4321,1324,4231
The parameter categories is a single ID or an array of different IDs. Here is the JSON data.
{
"data":
{
"1234":[
{"title":"Title 1 here", "description":"Content 1 here"},
{"title":"Title 2 here", "description":"Content 2 here"},
...
],
"4321":[
{"title":"Title 1 here", "description":"Content 1 here"},
{"title":"Title 2 here", "description":"Content 2 here"},
...
],
...
},
"message":"OK",
"code":0
}
Here is the PHP code. It works for the request to a single ID, but not different IDs.
<?php
require "vendor/autoload.php";
use Symfony\Component\DomCrawler\Crawler;
use GuzzleHttp\Client;
if (isset($_GET["c"]) && is_numeric($_GET["c"])) {
$category = $_GET["c"];
}
// DIFFERENT IDs
$url = "https://example.com/api/v2/content/?categories=1234,4321,1324,4231";
// SINGLE ID
$url = "https://example.com/api/v2/content/?categories=$category";
$client = new Client();
$response = $client->request("GET", $url);
$html = $response->getBody();
$decode = json_decode($html);
// $category works for a single ID but not multiple IDs
foreach ($decode->data->$category as $data) {
$title = $data->title;
$description = $data->description;
$result = array(
"title" => $title,
"description" => $description,
"category" => $category
);
$dataList[] = $result;
}
echo json_encode($dataList);
?>
Please let me know your recommendation to fetch API and merge arrays. The JSON result look like.
{
"data":
[
{"title":"Title 1 here", "description":"Content 1 here", "category":"1234"},
{"title":"Title 2 here", "description":"Content 2 here", "category":"4321"},
...
],
"page":1,
"message":"OK",
"code":0
}
Also, I'd like to limit results by adding a $_GET['page'].
In general, the above JSON result is what I expect. Please share your code or idea to get the best result. Thanks much for your anwser!. P/s: I'm not knowledgeble about coding, a web builder with low-code :(
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;
I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I'm getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php
$idtemp = extractfiles($fol_id, $email);
foreach ($idtemp['items'] as $val) {
$id = $val['id'];
$val = array(
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
);
$enc = json_encode($val);
$val = '{"files":['.$enc.']}';
echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
You should no do $val = '{"files":['.$enc.']}';
Use json_encode to make json, don't do it manual
Create an object with desired keys outside the loop
Push anything to the desired array
Convert to json
<?php
$idtemp = extractfiles($fol_id, $email);
$json = (object) [
"files" => []
];
foreach ($idtemp['items'] as $val) {
$json->files[] = (object) [
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
];
}
$json = json_encode($json);
echo($json);
If I use some dummy values to create an example, the output is:
{
"files": [
{
"webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk\""
}
]
}
As you can test in this online demo
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've got this PHP code
<?php
$json = file_get_contents('comments.json');
$decode = json_decode($json);
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
foreach($decode->comments as $key)
{
var_dump(array(
$key->name,
$key->email,
$key->comment
));
}
$decode->comments = array(array('name'=>$name, 'email'=>$email, 'comment'=>$comment));
$encode = json_encode($decode,JSON_FORCE_OBJECT);
file_put_contents('comments.json',$encode);
?>
It kind of works, it sets the current stuff in the JSON file to what its told to in this piece of PHP code. Instead of this, I want the PHP code to add on to the JSON that is already existing.
This is the JSON file.
{
"comments": {
"0": {
"name": "123",
"email": "123",
"comment": "123"
}
}
}
Pass a boolean true so you get an associative array instead of an object-based decode:
$json = file_get_contents('comments.json', true);
Change all of your OOP references to associative array style:
foreach($decode['comments'] as $key)
{
var_dump($key); // Declaring a whole new array isn't really needed here
}
Append to the decoded JSON array using the [] syntax:
$decode['comments'][] = array(
'name' => $name,
'email' => $email,
'comment' => $comment,
);
Re-encode and return the resulting JSON:
$encode = json_encode($decode, JSON_FORCE_OBJECT);
file_put_contents('comments.json',$encode);