I made an API CALL with Ecwid and I managed to get a JSON Response which works. This response sends me an Array that I can't find a way to use. I would like to write something who says " For each product in this json array please show its name " . This is what I have so far:
require_once('vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://app.ecwid.com/api/v3/83672989/products', [
'headers' => [
'Authorization' => 'Bearer secret_XYZ',
'accept' => 'application/json',
],
]);
echo $response->getBody();
foreach ($items in $response) {
echo "sku";
}
My JSON Looks like :
{
"total": 9,
"count": 9,
"offset": 0,
"limit": 100,
"items": [
{
"id": 523184135,
"sku": "0009",
"thumbnailUrl": "https://d2j6dbq0eux0bg.cloudfront.net/images/83672989/3416888569.jpg",
"unlimited": true,
"inStock": true,
"name": "EXEMPLE. Veste en jeans sans manches",
"nameTranslated": {
"fr": "EXEMPLE. Veste en jeans sans manches"
},
"price": 159.95,
"priceInProductList": 160,
"defaultDisplayedPrice": 160,
"defaultDisplayedPriceFormatted": "Fr160",
"costPrice": 0,
"tax": {
"taxable": true,
"defaultLocationIncludedTaxRate": 0,
"enabledManualTaxes": [],
"taxClassCode": "default"
},
I need to echo the SKU of items of this array in php for a wordpress page. I already tried a foreach loop on the json but it seems that I am not able to catch the data in json
Related
I have this JSON payload below and want to get names and ids from the payload. However, l cannot object names and ids from the payload.
Decode JSON
$result = json_decode($resp->getBody()->getContents(), true);
return response()->json(
[
"code" => 200,
"message" => "OK",
"payload"=> $result['payload'] ?? '',
]);
Api json payloads
{
"code": 200,
"message": "OK",
"payload": {
"items": [
{
"name": "Hostel",
"image": {
"name": "WEWEBBFC791FD50E347BD.jpeg"
},
"rate": {
"amount": "3.0000",
"currency": {
"code": "US"
}
},
"pricing": [
{
"rate": "3.0000"
}
],
"id": 12, // get this id
"created_at": "2021-02-28T11:08:25+00:00"
}
..........
],
"total": 10,
"offset": 10
}
}
Use json_decode to decode the json to an associative array, then access the elements of the array as you would any other assoc array.
It looks as though you can have one or more items in your collection, so you'll want to use a loop to iterate over them.
$decoded = json_decode($json, true);
foreach ($decoded['payload']['items'] as $item) {
$name = $items['name'];
$id = $items['id'];
dump($name, $id);
}
Here I am sharing response of API where i want to show to show specialization name in 'doctor_detail_data' array instead of "doctor_requests" array. In laravel using foreach loop . Below is my code:
$data['doctor_requests'] = DoctorRequests::where('caretaker_id', $caretaker_id)
->whereIn('status', $whereInArray)
->with('doctorUserData')->with('doctorDetailData')->get();
foreach ($data['doctor_requests'] as $key => $value) {
$data['doctor_requests'][$key]['specialization'] = Helpers::getSpecialisationName($value['doctorDetailData']['specialization']);
}
return ['code' => 200, 'status' => 'success', 'data' => $data, 'message' => 'Record fetched successfully.'];
Response :
{
"code": 200,
"status": "success",
"data": {
"doctor_requests": [
{
"id": 142,
"doctor_id": 432,
"caretaker_id": 429,
"patient_id": 433,
"specialization": "Oncology (Cancer Care)",
"doctor_user_data": {
"id": 432,
"name": "Sandeep Singh",
},
"doctor_detail_data": {
"id": 50,
"user_id": 432,,
"specialization": "3",
}
]
},
"message": "Record fetched successfully."
}
I want to redirect to an url that i have received in JSON from API.
<?php
include('yandex/lib/autoload.php');
use YandexCheckout\Client;
$client = new Client();
//$client->setAuth('', 'live_icDc3oRTP8kU3QWnyeeSsVE2-jeTHR0ZegtwGGrCqRw');
$client->setAuth('test', 'test_wOh1a3SNgOTaGuYNg5FzOEyDo11yg2KY9GqEJquyg3s');
$payment = $client->createPayment(
array(
'amount' => array(
'value' => 10.0,
'currency' => 'RUB',
),
'confirmation' => array(
'type' => 'redirect',
'return_url' => 'https://www.test.com/response.php',
),
'capture' => true,
'description' => 'Order No. 1',
),
uniqid('', true)
);
header('Content-Type: application/json');
$paymentarray = json_encode($payment);
print_r($paymentarray);
?>
here is the json print i have in browser.
{
"id": "258bf08a-000f-5000-a000-1882b803aeac",
"status": "pending",
"paid": false,
"amount": {
"value": "10.00",
"currency": "RUB"
},
"confirmation": {
"type": "redirect",
"confirmation_url": "https://money.yandex.ru/api-pages/v2/payment-confirm/epl?orderId=258bf08a-000f-5000-a000-1882b803aea"
},
"created_at": "2019-12-18T08:01:14.762Z",
"description": "Order No. 1",
"metadata": {},
"recipient": {
"account_id": "some",
"gateway_id": "some"
},
"refundable": false,
"test": true
}
i need to redirect it to the url, confirmation_url object received in json array using php.
i have tried following code to get data but its blank.
$paymentdata = json_decode($paymentarray, true);
echo $paymentdata['confirmation']['confirmation_url'];
echo $paymentdata['id'];
$data = json_decode($paymentarray,true);
$url = $data['confirmation']['confirmation_url'];
header("location:".$url);
From the json response posted, json_decode function returns an object, not an array. Try:
echo $paymentdata->confirmation->confirmation_url;
My data table that is loading its body from another file with ajax is giving me the invalid JSON error, but when I check my developer tools under network responses my JSON is valid?
This is my PHP and SQL:
<?php
header('Content-Type: application/json');
$output = array('data' => array());
$query = "SELECT * FROM table";
$stmt = sqlsrv_query($sapconn2, $query);
$x = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$output['data'][] = array(
'col_1' => $x,
'ID' => $row['ID'],
'QuoteID' => $row['QuoteID'],
'CardCode' => $row['CardCode'],
'SlpCode' => $row['SlpCode'],
'SlpName' => $row['SlpName'],
'BandA' => $row['BandA'],
'NewPrice' => $row['NewPrice']
);
$x ++;
}
echo json_encode($output);
?>
This is my JSON thats returned in the browser:
{
"data": [
[1, 138, 25, "000123", "222", "test data", 222, 222],
[2, 144, 25, "000123", "132", "test data", 465, 789],
[3, 160, 25, "000123", "456132", "test data", 5599, 5499],
[4, 171, 25, "000123", "789", "test data", 7897, 989],
[5, 172, 25, "000123", "11111", "test data", 1, 11],
[6, 182, 25, "000123", "132166", "test data", 1323, 133],
[7, 183, 25, "000123", "135456", "test data", 1332132, 13213],
[8, 184, 25, "000123", "1321", "test data", 5643214, 6513]
]
}
EDIT:
var testTable = $("#testTable").DataTable({
processing: false,
serverSide: true,
dataType : 'json',
ajax: "test.php",
columns: [
{ "data": "col_1" },
{ "data": "ID" },
{ "data": "QuoteID" },
{ "data": "CardCode" },
{ "data": "SlpCode" },
{ "data": "SlpName" },
{ "data": "BandA" },
{ "data": "NewPrice" }
]
});
This is what datatable waits for:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
...
]
}
The "data" element is an array of objects, instead you pass an array of array.
You need something like that:
{
"data": [
{ "id": 1, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
{ "id": 2, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
]
}
EDITED:
$output['data'][] = array(
'col_1' => $x,
'col_2' => $row['ID'],
'col_3' => $row['QuoteID'],
'col_4' => $row['CardCode'],
'col_5' => $row['SlpCode'],
'col_6' => $row['SlpName'],
'col_7' => $row['BandA'],
'col_8' => $row['NewPrice']
);
When you make a request to a server-side script from DataTables with processing set to true then it sends this data.
When it returns data DataTables expects the data to follow these conventions.
You can either take these into account with your server-side script (there's a good example here.) or choose a different method for adding your data. If you perhaps set processing to false you might find everything just works as you expect.
Hope that helps.
I am trying to loop through a json object and push selected values into an array.
$json = '
{
"canonicalUrl": "/v1/products(offers.type=deal_of_the_day)?format=json&apiKey=946n9vuhdkgeyz2qx2dpxd54",
"currentPage": 1,
"from": 1,
"partial": false,
"products": [
{
"active": true,
"activeUpdateDate": "2014-11-03T19:43:46",
"lowPriceGuarantee": true,
"name": "LG - 1.1 Cu. Ft. Mid-Size Microwave - Black",
"new": false,
"onSale": true,
"productId": 1219180376135,
"regularPrice": 124.99,
"salePrice": 99.99,
"sku": 5998225,
"source": "bestbuy",
"startDate": "2014-07-06",
"type": "HardGood"
},
{
"active": true,
"activeUpdateDate": "2014-11-03T18:03:02",
"lowPriceGuarantee": false,
"name": "Rocketfish In-Wall HDMI Cable",
"new": false,
"onSale": true,
"productId": 1218343205770,
"regularPrice": 29.99,
"salePrice": 24.99,
"sku": 2634897,
"source": "bestbuy",
"startDate": "2011-08-14",
"type": "HardGood"
}
],
"queryTime": "0.004",
"to": 2,
"total": 2,
"totalPages": 1,
"totalTime": "0.020"
}
';
$json_output = json_decode($json);
$pBB = array("title" => array(), "type" => array());
foreach($json_output->products as $obj){
array_push($pBB['title']," {$obj->name}");
array_push($pBB['type']," {$obj->type}" );
}
echo json_encode($pBB);
the output of above code is
{
"title": [
" LG - 1.1 Cu. Ft. Mid-Size Microwave - Black",
" Rocketfish In-Wall HDMI Cable"
],
"type": [
" HardGood",
" HardGood"
]
}
i want to to return it as below
[
{
"title": "LG - 1.1 Cu. Ft. Mid-Size Microwave - Black",
"type": "HardGood"
},
{
"title": " Rocketfish In-Wall HDMI Cable",
"type": " HardGood"
}
]
Any thoughts?
As per my comment on your question, you have used an unconventional method of organizing your products into values, where you should instead be organizing each product into separate array for each product containing its title and type. Use this instead:
$json_output = json_decode($json);
$pBB = array();
foreach($json_output->products as $obj){
$pBB[] = array(
'title' => " {$obj->name}", // Not sure why you're using " {$obj->name}" but I preserved it
'type' => " {$obj->type}", // You could just use $obj->type directly
);
}
echo json_encode(array_values($pBB));
$json_output = json_decode($json);
$pBB = array();
foreach($json_output->products as $obj){
array_push($pBB, array(
'title' => " {$obj->name}",
'type' => " {$obj->type}"
));
}
echo json_encode(array_values($pBB));
Try this! you need to create object and push into array.
$json = ' { "from": 1, "to": 2, "total": 2, "currentPage": 1, "totalPages": 1, "queryTime": "0.004", "totalTime": "0.020", "partial": false, "canonicalUrl": "/v1/products(offers.type=deal_of_the_day)?format=json&apiKey=946n9vuhdkgeyz2qx2dpxd54","products": [ { "sku": 5998225, "productId": 1219180376135, "name": "LG - 1.1 Cu. Ft. Mid-Size Microwave - Black", "source": "bestbuy", "type": "HardGood", "startDate": "2014-07-06","new": false, "active": true, "lowPriceGuarantee": true, "activeUpdateDate": "2014-11-03T19:43:46", "regularPrice": 124.99, "salePrice": 99.99, "onSale": true},{ "sku": 2634897, "productId": 1218343205770, "name": "Rocketfish In-Wall HDMI Cable", "source": "bestbuy", "type": "HardGood", "startDate": "2011-08-14", "new": false, "active": true,"lowPriceGuarantee": false, "activeUpdateDate": "2014-11-03T18:03:02", "regularPrice": 29.99, "salePrice": 24.99, "onSale": true } ] }';
$json_output = json_decode($json);
foreach($json_output->products as $obj){
$new_obj = new stdClass();
$new_obj->title = $obj->name;
$new_obj->type = $obj->type;
$pBB[]= $new_obj;
}
echo json_encode($pBB);
There is error with building JSON object. Actually the string you pass in json_decode function is okay, but problem occurs when you build an JSON object from array.
dont use
$pBB = array("title" => array(), "type" => array());
instead try
$pBB = array(array("title"=>$title,"type"=>$type));
When you encode $pBB into Json, i guess it will give you exact output.
Happy Coding.
Atul
echo json_encode($pBB);
You need to make sure it seems like it can be an array to JS (ie sequential numbering)
Replace the above line with
echo json_encode(array_values($pBB));
To make it work as expected
array values returns sequential ints as the keys