How to fetch API and merge arrays in PHP Guzzle - php

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 :(

Related

access data array in JSON with Laravel & Guzzle

I'm trying to retrieve data from an API that gives a response like so:
{
"data":[
{
"first_name":"John",
"last_name":"Smith",
"group":"3",
"email":"jsmith#talktalk.net"
},
{
"first_name":"John",
"last_name":"Doe",
"group":"3",
"email":"johndoe#aol.com"
}
],
"meta":{
"pagination":{
"total":2,
"count":2,
"per_page":500,
"current_page":1,
"total_pages":1,
"links":[
]
}
}
}
I'm trying to use Guzzle to import into my Laravel app
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://localhost/members.json');
$data = (string) $response->getBody();
and then a foreach to loop over each record and then add it to the database. Right now though I'm struggling to drill down into a record.
What am I missing?
EDIT: Here's the foreach
foreach ($data['data'] as $person) {
Contact::create(array(
'name' => $person->first_name,
));
}
Your $data variable holds json. Lets first make it a nice array and then loop it through
$response = json_decode($data, true);
Now the loop itself:
foreach($response['data'] as $element) {
$firstName = $element['first_name'];
$lastName = $element['last_name'];
$group = $element['group'];
$email = $element['email'];
//Now here you can send it to the modele and create your db row.
}

Search jsonarray for multiple values dynamically using php

i have a json array
[
{
"id":1.25,
"name":"rose",
"Number":15,
"SSN":[
12345,
3455
]
},
{
"id":1.15,
"name":"orchid",
"Number":7,
"SSN":[
12345,
3455
]
}
]
i want to get the id value if user searched with any ssn or name or by number.the input for search may not be single value that means it may be combination of ssn and name or it may be name,ssn and number .Any combination of name number ,ssn may be inputs .i have to get id value if the inputs matches using php .i used xpath for xml but i want to search fron json.can someone suggest me with any idea..thank you...
To search user ID by analyzing JSON string use the following approach with array_filter and array_intersect_assoc functions:
$json_str = '[ { "id":1.25, "name":"rose", "Number":15, "SSN":[ 12345, 3455 ] }, { "id":1.15, "name":"orchid", "Number":7, "SSN":[ 12345, 3455 ] }]';
$decoded = json_decode($json_str, true);
// base search structure
$search_structure = ['name' => "", 'Number' => 0];
// let's say, the following inputs have come from API (some of them may be empty or omitted)
$number = 7;
$ssn = "3455";
if ($number && is_numeric($number)) $search_structure['Number'] = $number;
$search_structure = array_filter($search_structure); // filtering out empty params
$count_params = count($search_structure);
$user_id = 0;
foreach ($decoded as $item) {
if ($count_params == count(array_intersect_assoc($search_structure, $item))) {
if (!$ssn || ($ssn && in_array($ssn, $item['SSN']))) {
$user_id = $item['id'];
break;
}
}
}
print_r(($user_id)? "User id: $user_id" : "User with specified params not found!");
The output:
User id: 1.15
Lets $json contains an array string
$ar = json_decode($json, true);
$id = false;
foreach ($ar as $i)
if ($i["name"] == "rose" and $i["Number"] == 15)
{ $id = $i["id"]; break; }
if ($id !== false) {
// use $id
}
Preferably, convert the json data to native PHP Object and then using foreach, loop over the object and extracting the ID of the Objects that match the given SSN Number. The result of the extraction would be assigned to an array. Below is a Commented procedure of 1 possible way of going about this:
<?php
// WE ASSUME, JUST FOR TESTING PURPOSES THAT THE SSN NUMBER WE ARE LOOKING FOR IS 4567
$ssnNumber = 4567; //3455;
// CREATE A NEW ARRAY VARIABLE TO HOLD THE IDs YOU DESIRE & INITIALIZE IT TO AN EMPTY ARRAY
$arrIDS = array();
$jsonData = '[
{
"id" :1.25,
"name" :"rose",
"Number" :15,
"SSN" :[
12345,
3455
]
},
{
"id" :1.15,
"name" :"orchid",
"Number" :7,
"SSN" :[
12345,
3455
]
},
{
"id" :1.75,
"name" :"orchid",
"Number" :79,
"SSN" :[
4567,
89012
]
}
]';
// CONVERT $jsonData TO NATIVE PHP OBJECT
$objJson = json_decode($jsonData);
// LOOP THROUGH THE PHP OBJECT & TEST IF A GIVEN SSN EXIST.
foreach($objJson as $key=>$data){
// CHECK IF THE $data->SSN IS SET:
if(isset($data->SSN) && is_array($data->SSN)){
// CHECK IF THE SSN ARRAY CONTAINS THE GIVEN SSN NUMBER.
if(in_array($ssnNumber, $data->SSN)){
$arrIDS[] = $data->id;
}
}
}
var_dump($arrIDS); // DISPLAY: array (size=1) 0 => float 1.75
Alternatively, one could as well encapsulate the above Routine withina Function for re-usability like so:
<?php
function getIDBySSN($jsonData, $ssnNumber){
$arrIDs = array();
$objJson = json_decode($jsonData);
// LOOP THROUGH THE PHP OBJECT & TEST IF A GIVEN SSN EXIST.
foreach($objJson as $key=>$data){
// CHECK IF THE $data->SSN IS SET:
if(isset($data->SSN) && is_array($data->SSN)){
// CHECK IF THE SSN ARRAY CONTAINS THE GIVEN SSN NUMBER.
if(in_array($ssnNumber, $data->SSN)){
$arrIDs[] = $data->id;
}
}
}
return $arrIDs;
}
var_dump(getIDBySSN($jsonData, $ssnNumber)); // PRODUCES THE SAME RESULT
Test it HERE:

Trying to create a JSON in php with an Image as URL and create an ID to each image

Trying to create a json encode with a ID and a image URL so i can reach it as a jobject in my frontend.
I am not working with a MySQL here as I store the images on my map/file manager.
I want it to look like this when when the code runs:
{
results: [
{
ID: "3",
URL: "http://www.image.com/Images/image3.jpg"
} ]
}
So I want to connect an image to a certain IP and also get its URL.
This is my code so far:
<?php
$contacts = array();
$contact = array("URL" => $row ['http://www.image.com/Images/image1.jpg'],
$row ['http://www.image.com/Images/image2.jpg'],
$row ['http://www.image.com/Images/image3.jpg'],
"ID" => $row ['1'], $row ['2'], $row ['3']);
array_push($contacts, $contact);
echo json_encode(array('results' => $contacts), JSON_PRETTY_PRINT);
?>
Still don't see $row.. Anyway, I think what you want is something like this :
<?php
$contacts = array();
$contacts[] = array("id"=>1,"URL"=>'http://www.image.com/Images/image1.jpg');
$contacts[] = array("id"=>1,"URL"=>'http://www.image.com/Images/image2.jpg');
$contacts[] = array("id"=>1,"URL"=>'http://www.image.com/Images/image3.jpg');
echo json_encode(array('results' => $contacts), JSON_PRETTY_PRINT);
Example https://3v4l.org/uRbQ7

How to do prefix query in Elasticsearch php?

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

json-decode two feed sources

I am try to decode two different json feed urls and merge into one oject/output. I have tried the below, however, not really having much luck.
feed source 1: http://sourcesample.com/feed/posts
data: [
{
name: "Me",
url: "http://example.com/sample",
title: "Sample Title",
}
]
feed source 2: http://differentsource.com/feed/details
data: [
{
likes: "200",
shares: "300",
total: "1000",
}
]
$sources =array("http://sourcesample.com/feed/posts", "http://differentsource.com/feed/details");
$requests = file_get_contents($sources[0],$sources[1]);
$response = json_decode($requests);
foreach($response->data as $item){
echo'<li>'.$item->name.'</li><li>'.$item->shares.'</li>'
Printing the name works, but when trying to print the second object feed, nothing. Any ideas?
file_get_contents() won't return more than one URL's contents at a time. The second parameter is being treated as true, roughly, for the use_include_path parameter. For your purposes, it's irrelevant.
Anyway, only the first feed is read. It includes no "shares" data.
Even if both were read, the result would be:
'data: [
{
name: "Me",
url: "http://example.com/sample",
title: "Sample Title",
}
]
data: [
{
likes: "200",
shares: "300",
total: "1000",
}
]'
which is not a valid JSON string - it's two objects next to each other, not merged.
If you're really confident that both feeds are the same size, you can read them both (separately) then loop through them at once:
$names = json_decode( file_get_contents( $sources[0] ) );
$stats = json_decode( file_get_contents( $sources[1] ) );
for ( $i = 0; $i < count( $names->data ); ++$i )
{
$name = $names->data[$i];
$stat = $stats->data[$i];
echo '<li>' . htmlspecialchars($name->name) . '</li><li>' .
htmlspecialchars($stat->shares) . '</li>';
}

Categories