This is the array:
$response = array( 'message-count' => '1', 'messages' => array ( 0 => array ( 'to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111', ), ), );
What code do I use to get like, for example, the 'message-id' 's data?
I've tried $response->messages["message-id"];
but what I get is Trying to get property 'messages' of non-object
Tried a lot of others as well they are all returning the same error
I am quite new to this so I hope I could get some help here
Sorry:
Vardump gives me this, made a mistake with the code above
'{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}'
response is an array, you can't get messages like -> , You should get message-id by this way:
$jsonStr = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($jsonStr);
$messageId = $data->messages[0]->{'message-id'};
echo $messageId; //or var_dump($messageId)
Your array contains non-object values so you can retrieve the values as below.
<?php
$response = array('message-count' => '1', 'messages' => array(0 => array('to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111',),),);
echo $response['messages'][0]['message-id'];
// Output
// XXXXXXXXXXX
I would use array_column function like this
array_column($response['messages'], 'message-id');
$msg = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($msg);
$messageId = $data->messages[0]->{'message-id'};
var_dump($messageId);
If you have more than one message in the list then,
$messages = $data->messages;
foreach ($messages as $index => $message) {
var_dump($message); // whole message detail
var_dump($message->{'message-id'});// message-id
}
Related
I'm trying to send this data in a request:
{
"TABLENAME":"USERS",
"DATA": [
{
"ID": "1",
"NAME":"JOHN",
"AGE":"33",
"GENDER":"M",
"DATE":"2000000",
"CITY":"LONDON"
},
{
"ID": "2",
"NAME":"MARK",
"AGE":"35",
"GENDER":"M",
"DATE":"2000000",
"CITY":"MUNICH"
}
]
}
I'm retrieving all the hook data and storing it in my hook handler like:
$data = $this->webhookCall;
And access the payload through:
$payload = $data->payload;
The $payload first of all is an array and the key values are in reverse order, and looks like this:
array (
'DATA' =>
array (
0 =>
array (
'ID' => '1',
'AGE' => '33',
'CITY' => 'LONDON',
'DATE' => '2000000',
'NAME' => 'JOHN',
'GENDER' => 'M',
),
1 =>
array (
'ID' => '2',
'AGE' => '35',
'CITY' => 'MUNICH',
'DATE' => '2000000',
'NAME' => 'MARK',
'GENDER' => 'M',
),
),
'TABNAME' => 'USERS',
)
Also when trying to save to db:
$hook = new USER;
$hook->name = $data->name;
$hook->url = $data->url;
$hook->headers = json_encode($data->headers);
$hook->payload = json_encode($data->payload);
$hook->exception = $data->exception;
$hook->save();
The data is still with the wrong key order:
{"DATA": [{"ID": "1", "AGE": "33", "CITY": "LONDON", "DATE": "2000000", "NAME": "JOHN", "GENDER": "M"}, {"ID": "2", "AGE": "35", "CITY": "MUNICH", "DATE": "2000000", "NAME": "MARK", "GENDER": "M"}], "TABNAME": "USERS"}
I have tried to reverse the $payload array:
$hook->payload = json_encode(array_reverse($data->payload));
but the data is still in the wrong order in the db.
Can someone please tell me what is wrong here and why this behavior?
And also why does an object sent in a request is being converted to an array? Is this normal behavior for php or specific for this package that I'm using?
Thanks
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How can I replace a specific key's value in an array in php?
(2 answers)
Closed 7 months ago.
I all, I've been staring at this for hours so any help is greatly appreciated. I have an array...
$aircraft = [
'N7826C' => ['nnum' => 'N7826C', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N226PD' => ['nnum' => 'N226PD', 'name' => 'ANAHEIM POLICE DEPT', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N326PD' => ['nnum' => 'N326PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0'],
'N826PD' => ['nnum' => 'N826PD', 'name' => 'CITY OF ANAHEIM', 'icon' => 'police', 'lat' => '', 'lng' => '', 'status' => '0']
];
With that array, I implode it to get a list of the nnums to pass through a API....
$aircraftNNUMlist = implode(',', array_map(function($v) { return $v['nnum']; }, $aircraft));
$json = file_get_contents('https://airlabs.co/api/v9/flights?_fields=reg_number,lat,lng®_number='.$aircraftNNUMlist.'&api_key=XXXXX');
That API returns...
{
"request": {
"lang": "en",
"currency": "USD",
"time": 15,
"id": "c9by9lmq1q0",
"server": "z",
"host": "airlabs.co",
"pid": 322387,
"key": {
"id": 19146,
"api_key": "xxxxxxxxxxxxxxxx",
"type": "free",
"expired": "2022-08-20T22:00:00.000Z",
"registered": "2022-07-19T03:51:04.000Z",
"limits_by_hour": 2500,
"limits_by_minute": 250,
"limits_by_month": 1000,
"limits_total": 628
},
"params": {
"_fields": "reg_number,lat,lng",
"reg_number": "N60NT,N40NT,N30NT,N10NT",
"lang": "en"
},
"version": 9,
"method": "flights",
"client": {
"ip": "xxxxxxxxxxxxxxxxx",
"geo": {
"country_code": "US",
"country": "United States",
"continent": "North America",
"city": "Provo",
"lat": 40.2181,
"lng": -111.6133,
"timezone": "America/Denver"
},
"connection": {
"type": "corporate",
"isp_code": 46606,
"isp_name": "Unified Layer"
},
"device": {},
"agent": {},
"karma": {
"is_blocked": false,
"is_crawler": false,
"is_bot": false,
"is_friend": false,
"is_regular": true
}
}
},
"response": [
{
"reg_number": "N60NT",
"lat": 34.11,
"lng": -117.69
}
],
"terms": "Unauthorized access is prohibited and punishable by law. \nReselling data 'As Is' without AirLabs.Co permission is strictly prohibited. \nFull terms on https://airlabs.co/. \nContact us info#airlabs.co"
}
I am having trouble looping through the "response" of the API return (stored at $json) to update the corresponding index in $aircraft. If a nnum isn't currently active there will not be a entry in "response" for instance "response" only has N60NT in the return array. I am fairly new to arrays so I've been taking swings in the dark and nothing seems to be right.
I presume you have json_decoded your api json response into a PHP array. Well actually:
$arr = json_decode($json_form_api, true);
$response = $arr["response"];
foreach ($response as $sub) {
$reg = $sub["reg_number"];
$aircraft[$reg]["lat"] = $sub["lat"];
$aircraft[$reg]["lng"] = $sub["lng"];
}
I have created an array to convert into json file in php. But as per the requirement I need to assign an array to this array element. it's an array inside an array.
"data" => array( // data array
array(
"event_name" => "Purchase",
"event_time" => time(),
"event_id" => $order_id,
"user_data" => array(
"client_ip_address" => $ip,
"client_user_agent" => $browser,
"em" => $email,
"ph" => $phone,
"fbc" =>$fbp,
"fbp" =>$fbc,
"fn" => $fn,
"ct" => $ct,
"st" => $st,
"zp" => $zp,
"country" => $country,
"external_id" => $email
),
"contents" => $items,
// "id" => $item_ids,
// "quantity" => count($item_qty),
// // "delivery_category"=> "home_delivery",
// "order_id" => $order_id
// ),
"custom_data" => array(
"currency" => "GBP",
"value" => $order_total,
),
"action_source" => "website",
"event_source_url" => $fullURL,
),
)
);
But my $item array look like this when I echo
{
"id": 814,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Certificate in Strategic Management and Leadership (RQF)",
"product_id": 19555,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "1158",
"subtotal_tax": "0",
"total": "1158",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
},
{
"id": 815,
"order_id": 36956,
"name": "Pearson BTEC Level 7 Diploma in Strategic Management and Leadership (RQF)",
"product_id": 19107,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "999",
"subtotal_tax": "0",
"total": "999",
"total_tax": "0",
"taxes": {
"total": [],
"subtotal": []
},
"meta_data": []
}
And when I assign this $items and converted to json then I can see only the ides of the array
"user_data": {
"client_ip_address": "2402:d000:a200:a4a8:f06d:40a:cf85:e26d",
"client_user_agent": "",
"em": "b99526fedef7fe1da29e27d6f09cb64efew536978778e6cde3d8277d71a04398d1a4",
"ph": "db80005a39b11372054b7708cac76gsaaww47af6ed3fe4b37b9a8b2be435e2fcff04a7",
"fbc": "",
"fbp": "",
"fn": "83cd072a16ddb3d793c2f5bcd7d0basdree5a04af680279cf6a26fb8dffe57ce3b51a",
"ct": "17a0730b80e55f4bee9569be3f7e6d0wqw500c5568ecb8d785759d7151ef40f5bbd",
"st": "e3b0c44298fc1c149afbf4c8996fb9sas2427ae41e4649b934ca495991b7852b855",
"zp": "ac7bb74de6884ffce919c15fef4193749sdsd4588026c643973946713ac46da540d",
"country": "c820736841e811c96d30b14eb998feb6bsddc2c9d0764b7731267438dc7d6bb5b59",
"external_id": "b99526fedef7fe1da29e27d6f09ssscb64536978778e6cde3d8277d71a04398d1a4"
},
"contents": [
{
"814": {},
"815": {}
}
],
result should be look like this in this way in "centents" element
"contents" : [{'id':'ABC123','quantity' :2,'item_price':5.99}, {'id':'XYZ789','quantity':2, 'item_price':9.99, 'delivery_category': 'in_store'}]
I think the problem is that your $items, is actually an array of "strings" (json)
try to do a json_decode() on those $items before adding it to the content.
anyway, when you ask a question try to remove all unnecessary stuff, and make an example with the minimum code you need help with, in this case it takes a lot of reading through stuff just to understand the issue.
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;
I am using sports-radar API to get the schedule of NFL week 1. The API returns the following data in json format (I shortened string for example).
"id": "8e45fe2d-fb95-4504-845d-7c815623ccd6",
"year": 2018,
"type": "REG",
"name": "REG",
"week": {
"id": "37435167-5cf6-4cce-b405-ff0e264ced9c",
"sequence": 1,
"title": "1",
"games": [{
"id": "0822b924-eadc-4398-bfe6-83cbbf3a2912",
"status": "scheduled",
"reference": "57570",
"number": 4,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "6ed18563-53e0-46c2-a91d-12d73a16456d",
"name": "Lucas Oil Stadium",
"city": "Indianapolis",
"state": "IN",
"country": "USA",
"zip": "46225",
"address": "500 South Capitol Avenue",
"capacity": 67000,
"surface": "artificial",
"roof_type": "retractable_dome"
},
"home": {
"id": "82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9",
"name": "Indianapolis Colts",
"alias": "IND",
"game_number": 1
},
"away": {
"id": "ad4ae08f-d808-42d5-a1e6-e9bc4e34d123",
"name": "Cincinnati Bengals",
"alias": "CIN",
"game_number": 1
},
"broadcast": {
"network": "CBS"
}
}, {
"id": "0a456149-c547-4856-9b1b-86e1d93887ae",
"status": "scheduled",
"reference": "57574",
"number": 8,
"scheduled": "2018-09-09T17:00:00+00:00",
"entry_mode": "INGEST",
"venue": {
"id": "3c85d89a-ec66-4983-acd5-1381d6c8673a",
"name": "Mercedes-Benz Superdome",
"city": "New Orleans",
"state": "LA",
"country": "USA",
"zip": "70112",
"address": "1500 Sugar Bowl Drive",
"capacity": 73208,
"surface": "artificial",
"roof_type": "dome"
},
"home": {
"id": "0d855753-ea21-4953-89f9-0e20aff9eb73",
"name": "New Orleans Saints",
"alias": "NO",
"game_number": 1
},
"away": {
"id": "4254d319-1bc7-4f81-b4ab-b5e6f3402b69",
"name": "Tampa Bay Buccaneers",
"alias": "TB",
"game_number": 1
},
"broadcast": {
"network": "FOX"
I used the following website as a tutorial on how to display only the the data I need and how to loop over it
Note the JSON string is stored in the variable $schedule
MY Code
// JSON string
$jsonData = $schedule; //get json string
// Convert JSON string to Array
$jsonArray = json_decode($jsonData, true);
// Convert JSON string to Object
$jsonObject = json_decode($schedule);
Looping through PHP Array or Object
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"] . ", " . $value["away"] . "<br>";
}
// Loop through Object
$someObject = jsonObject
foreach($someObject as $key => $value) {
echo $value->home . ", " . $value->away . "<br>";
}
My ERRORS
When trying to convert the string to an array and attempting to get the away team name I get the error Illegal string offset 'away' same problem with home and all other data
When trying to access data as an object I get the following error Trying to get property of non-object
I followed the tutorial to the letter. Yet im getting the basic errors above...? Any help and explanation would be appreciated. Thank you
EDIT:
var_export($schedule) returns the following:
array ( 'id' => '8e45fe2d-fb95-4504-845d-7c815623ccd6', 'year' => 2018, 'type' => 'REG', 'name' => 'REG', 'week' => array ( 'id' => '37435167-5cf6-4cce-b405-ff0e264ced9c', 'sequence' => 1, 'title' => '1', 'games' => array ( 0 => array ( 'id' => '0822b924-eadc-4398-bfe6-83cbbf3a2912', 'status' => 'scheduled', 'reference' => '57570', 'number' => 4, 'scheduled' => '2018-09-09T17:00:00+00:00', 'entry_mode' => 'INGEST', 'venue' => array ( 'id' => '6ed18563-53e0-46c2-a91d-12d73a16456d', 'name' => 'Lucas Oil Stadium', 'city' => 'Indianapolis', 'state' => 'IN', 'country' => 'USA', 'zip' => '46225', 'address' => '500 South Capitol Avenue', 'capacity' => 67000, 'surface' => 'artificial', 'roof_type' => 'retractable_dome', ), 'home' => array ( 'id' => '82cf9565-6eb9-4f01-bdbd-5aa0d472fcd9', 'name' => 'Indianapolis Colts', 'alias' => 'IND', 'game_number' => 1, ),
You are dealing with array of arrays. Try something like this:
$someArray = $jsonArray
foreach ($someArray as $key => $value) {
echo $value["home"]["name"] . ", " . $value["away"]["name"] . "<br>";
}