Trying to get property name and id of laravel payload - php

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

Related

Here I am sharing response of API Using Laravel in which i want to specialization name in 'doctor_detail_data' array instead of 'doctor_requests'

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."
}

PHP value from JSON

I have a problem with JSON Array. How i can get value from 'orders' -> 'status'
This is body JSON body
{
"orders": [
{
"orderId": "F3MXBWMG61151028GUEST000P01",
"orderCreateDate": "2015-10-28T09:24:45.318+01:00",
"notifyUrl": "http://server/payuint2/main/notify2",
"customerIp": "127.0.0.1",
"merchantPosId": "200003",
"description": "TEST",
"currencyCode": "USD",
"totalAmount": "15000",
"status": "NEW",
"products": [
{
"name": "TEST",
"unitPrice": "15000",
"quantity": "1"
}
]
}
],
"status": {
"statusCode": "SUCCESS",
"statusDesc": "Request processing successful"
}
}
I'm trying to use the code for now
$order_info_payu = json_decode($response,true);
$order_status = $order_info_payu->orders->status;
or
$order_status = $order_info_payu['orders']['status'];
when I only use
$order_status = $order_info_payu['orders']
then I have the content, but how to capture 'status' from 'orders'?
Now its working.
$order_status = $order_info_payu->orders[0]->status;
echo $order_status;
Inside orders object you have an array thats why you need to add ..->orders[0]->..
see there is an
{
"orders": [ .... /* square brackets = an array inside the order object,*/
]
}
this square brackets means that after order object there is an array and then inside that array there are other objects.

php json response formatting as per requirement

I am returning json response to api, using json_encode() method.
I have array which is where a key users can have multiple user or no user i.e empty array,and key course is either empty or can have single object as below
{
"success": true,
"code": 200,
"message": "",
"result": {
"users": [],
"course": []
}
}
if it has data the response is like this
{
"success": true,
"code": 200,
"message": "",
"result": {
"users": [
{
"name": "Vishal",
"Age": 25
},
{
"name": "Akshay",
"Age": 29
}
],
"course": {
"name": "xyz"
}
}
}
but what i want is users should be array in both cases and course should return as object in both cases. is it possible.??
You can force course entry to be object before json encoding.
$ret["result"]["course"] = (object)$course;

Delete object from json file with PHP

Well, I have a web project and I have to be saving things temporarily, I started work with a json file, so far I can add and update.
The json file looks like this:
[
{
"username": "Baldwin",
"products": [
{
"id": 0,
"amount": 10
},
{
"id": 1,
"amount": 9
},
{
"id": 2,
"amount": 9
}
]
},
{
"username": "Alice",
"products": [
{
"id": 0,
"amount": 11
},
{
"id": 1,
"amount": 13
},
{
"id": 2,
"amount": 6
}
]
},
{
"username": "Terry",
"products": [
{
"id": 0,
"amount": 12
},
{
"id": 1,
"amount": 14
},
{
"id": 2,
"amount": 5
}
]
}
]
The problem comes when I want to delete an specific array or when I want to delete it completely, I can do it and it works fine, but I have the doubt about why when I delete the object, other fields are add to the json file, like an id.
When i delete just one product inside of the "products" array something like this happen:
[
{
"username": "Baldwin",
"products": { "1": { "id": 1, "amount": 9 }, "2": { "id": 2, "amount": 9 } }
},
{
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
{
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
]
And when i delete a complete array from the json file, something like this happen:
{
"1": {
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
"2": {
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
}
My php file to delete:
<?php
// load file
$data = file_get_contents('results.json');
// decode json to associative array
$json_arr = json_decode($data, true);
$flag = false;
// We check if the user wants to delete all or just one product
if(isset($_POST["all"])):
$username = $_POST["username"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
unset($json_arr[$key]);
break;
endif;
endforeach;
elseif(isset($_POST["one"])):
$username = $_POST["username"];
$id = $_POST["id"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
// loop products of the current username
foreach ($json_arr[$key]["products"] as $k => $product):
// find the id of the product
if($json_arr[$key]["products"][$k]["id"] == (int)$id):
// delete the product
unset($json_arr[$key]["products"][$k]);
endif;
endforeach;
endif;
endforeach;
endif;
// encode json and save to file
file_put_contents('results.json', json_encode($json_arr));
// redirect to show.php
header("Location: show.php");
?>
I've been taking a look to questions like this one but i couldn't find something with php, i would like to know how to solve this or if this is normal.
What happens when you use unset($json_arr[0]) is that the first element is removed, but the keys are not updated. If you inspect the array after the removal, you'll find that your array has two elements, at $json_arr[1] and $json_arr[2].
When you then perform a json_encode($json_arr) on this, PHP's JSON decoder looks at the array and since arrays are supposed to begin at the 0th element but this array begins at 1, it decides that in order to preserve the keys, the array would have to be converted to an associative array - which transforms the integer array keys into string keys in JSON.
For a short and quick solution, you can try:
$json_arr = array_diff($json_arr, [$key]);
You could even use array_splice or array_values - see here for inspiration.

fetch values from array within an array

I have a multidimensional array, i wish to extract each value from this array.
The array is stored in $data.
{"success":true,"categories":
[
{"
category_id":"C1",
"parent_id":"P1",
"name":"N1",
"categories":
[
{
"category_id":"C11",
"parent_id":"P11",
"name":"N11",
},
{
"category_id":"C12",
"parent_id":"P12",
"name":"N12",
},
],
"status":"1"
},
{
category_id":"C2",
"parent_id":"P2",
"name":"N2",
"categories":
[
{
"category_id":"C21",
"parent_id":"P21",
"name":"N21",
[
{
"category_id":"C22",
"parent_id":"P23",
"name":"N24",
}
],
"status":"2"
}
],
"status":"3"
},
]
}
I tried using
$total = $data['categories']['category_id'];
to fetch value C11
but wasn't able to do so.
can anyone tell how i can fetch all the data especially C22
You have to first use json_decode.
$array = json_decode($data, true);
Then you can access the array as you have stated.
Or loop throught the categories:
if (!empty($array)) {
foreach ($array['categories'] as $category) {
echo $category['id'];
}
}
You may have to do this recursively to loop through the categories within the categories. But it depends completely what you want to achieve. A nested loop could do the job if it is always just one level deep.
EDIT
The JSON you have provided is not quite right, I have given a corrected one below:
{
"success": true,
"categories": [
{
"category_id": "C1",
"parent_id": "P1",
"name": "N1",
"categories": [
{
"category_id": "C11",
"parent_id": "P11",
"name": "N11"
},
{
"category_id": "C12",
"parent_id": "P12",
"name": "N12"
}
],
"status": "1"
},
{
"category_id": "C2",
"parent_id": "P2",
"name": "N2",
"categories": [
{
"category_id": "C21",
"parent_id": "P21",
"name": "N21",
"categories": [
{
"category_id": "C22",
"parent_id": "P23",
"name": "N24"
}
],
"status": "2"
}
],
"status": "3"
}
]
}
There were a few trailing commas and missing quote marks.
The data is not in PHP array, its a JSON array. You have to decode it, by using json_decode() function.
That's JSON, not php multidimensional array. You can use json_decode function to read through it.

Categories