Can I get a specific JSON value by Id? - php

I would like to have the corresponding date of typeId: 11 output from the following JSON.
The order of the typeId's is always different, so it doesn't always work, for example, to always address the second value.
{
"page": 1,
"totalsCount": 1,
"isLastPage": true,
"lastPageNumber": 1,
"firstOnPage": 1,
"lastOnPage": 1,
"itemsPerPage": 50,
"entries": [
{
"id": 60132,
"statusName": "GIT",
"dates": [
{
"orderId": 60132,
"typeId": 7,
"date": "2021-06-03T00:00:00+02:00"
},
{
"orderId": 60132,
"typeId": 11,
"date": "2021-05-28T00:00:00+02:00"
},
{
"orderId": 60132,
"typeId": 16,
"date": "2021-05-27T20:20:28+02:00"
},
{
"orderId": 60132,
"typeId": 2,
"date": "2021-05-27T20:19:21+02:00"
},
{
"orderId": 60132,
"typeId": 4,
"date": "2021-06-03T15:16:14+02:00"
}
]
}
]
}
With my approach so far, I don't get any result:
$json = file_get_contents($orders);
$arr = json_decode($orders);
foreach($arr->entries as $order => $value) {
echo '<th scope="row">' . $value->dates->[typeId='11'].date . '</th>';
}
Where is my mistake here?

You could use array_map():
<?php
$arr = json_decode($json, true);
$result = array_filter(
array_map(
function ($record) {if($record['typeId'] == 11) return $record['date'];}, $arr['dates']
)
);
use array_filter() to remove empty values from the result-set.
working demo
EDIT
With updated json information, you could use:
$obj = json_decode($json);
foreach($obj->entries[0]->dates as $order => $value) {
if($value->typeId == 11) echo '<th scope="row">' . $value->date . '</th>';
}
working demo

For this kind of situation i usually write a simple function like this:
function getDate(array $dates, $typeId) {
foreach ($dates as $date) {
if ($date['typeId'] === $typeId) {
return $date;
}
}
return null;
}

Because the dates is an array you have to iterate over and filter out the proper elements by typeId.
Something like this:
dates.filter(({typeId}) => typeId === 11).shift().date

Related

Laravel - Format JSON

I have a code that outputs the json result below:
{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}
Now how can I format it in the my desired json format below:
Note* I have to remove some result.
{
"Ghost in the Shell":
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
Will appreciate if anyone can help me please.
I am not sure what is your purpose , but here is what you need
<?php
$json = '{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}';
$array = json_decode($json, true);
$newArray = array();
foreach($array as $key=>$value) {
$newArray[$key] = '';
foreach($value as $k=>$v) {
if(is_array($v)) {
$newArray = array_merge($newArray,$v);
}
}
}
$newJson = json_encode($newArray);
echo $newJson;
?>

access to properties of an array contain json formatted elements in laravel

suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>

Retrieve data (single field) from remote JSON file with PHP

i need to extract one field from a JSON file. From other questiones i've manage to come to this code but the output is a blank page. Can you see what this n00b doing wrong?
<?php
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json);
$tasa=$details->USD[0]->transferencia;
echo .$tasa.;
?>
The json file looks like this:
{
"_antibloqueo": {
"mobile": "https://dkqrwi4z9077n.cloudfront.net",
"video": "https://www.youtube.com/embed/videoseries?list=PL6qOmJKmpQ8QMt20uG_dlh9-jzjcvZOxU&showinfo=0",
"corto_alternativo": "https://bit.ly/venezuela911",
"enable_iads": "1",
"alternativo": "68747470733a2f2f643271737267626d6d76366561752e636c6f756466726f6e742e6e6574",
"alternativo2": "68747470733a2f2f73686431613934666462346474697662672e776f726473736c2e6e6574",
"resource_id": "33504 C"
},
"_labels": {
"a": "DOLARTODAY",
"b": "IMPLICITO",
"c": "SIMADI",
"d": "SICAD 2",
"e": "CENCOEX"
},
"_timestamp": {
"epoch": "1434016329",
"fecha": "Junio 11, 2015 05:22 AM",
"fecha_corta": "Jun 11, 2015",
"fecha_nice": "Junio 11, 2015",
"dia": "Jueves",
"dia_corta": "Jue"
},
"USD": {
"transferencia": 414.18,
"transfer_cucuta": 435.00,
"efectivo": 145.72,
"efectivo_real": 357.61,
"promedio": 414.18,
"promedio_real": 195.94,
"cencoex": 6.30,
"sicad1": 12.00,
"sicad2": 195.94,
"dolartoday": 414.18
},
"EUR": {
"transferencia": 466.57,
"transfer_cucuta": 489.98,
"efectivo": 164.14,
"efectivo_real": 402.84,
"promedio": 466.57,
"promedio_real": 220.71,
"cencoex": 7.10,
"sicad1": 13.52,
"sicad2": 220.71,
"dolartoday": 466.57
},
"COL": {
"compra": 6.70,
"venta": 7
},
"GOLD": {
"rate": 1180.0500
},
"USDVEF": {
"rate": 6.3500
},
"USDCOL": {
"rate": 2775.00,
"ratecash": 2396.00,
"ratetrm": 2523.00,
"trmfactor": 0.1,
"trmfactorcash": 0.05
},
"EURUSD": {
"rate": 1.1264
},
"BCV": {
"fecha": "1433824200",
"fecha_nice": "Junio 9, 2015",
"liquidez": "2.457.797.346",
"reservas": "16.867.000"
}
}
You just make mistake in USD[0] and 2 dots when echoing $tasa
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json);
$tasa=$details->USD->transferencia;
echo $tasa;
I have tested your json, you can access data via multidimensional arrays like below:
<?php
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json , true);
print_r( $details['USD']['transferencia'] );
?>
Try this:
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json, TRUE);
var_dump($details['USD']['transferencia']);

Accessing nested JSON using PHP

I've created the most part and it's working fine. But this is the only JSON that is nested. How do I access it? I've been trying for the longest time, I think I may have a brain freeze because I thought it would be so simple.
Here is the code to GET all reservations from the JSON file:
GET - Gets all Reservation by Status
$app->get('/reservation/:status', function($status) {
$dbHandler = new DatabaseHandler();
$dbHandler->connect();
$reservationArray = $dbHandler->runQueryWithOneParam('SELECT * FROM RestaurantDB.Reservation WHERE STATUS = ?', "s", $status);
$response = array();
$response["error"] = false;
$response["reservations"] = array();
while ($reservation = $reservationArray->fetch_assoc()) {
$tmpReservation = array();
$tmpReservation["ID"] = $reservation["ID"];
$tmpReservation["UserName"] = $reservation["UserName"];
$tmpReservation["NoOfPeople"] = $reservation["NoOfPeople"];
$tmpReservation["DateOfReservation"] = $reservation["DateOfReservation"];
$tmpReservation["TimeOfReservation"] = $reservation["TimeOfReservation"];
$tmpReservation["Status"] = $reservation["Status"];
$tmpReservation["TotalAmount"] = $reservation["TotalAmount"];
$tmpReservation["SpecialRequirement"] = $reservation["SpecialRequirement"];
$tmpReservation["Details"] = array();
$reservationDetailArray = $dbHandler->runQueryWithOneParam('SELECT * FROM RestaurantDB.ReservationDetail WHERE ReservationID = ?', "i", $reservation["ID"]);
while ($reservationDetail = $reservationDetailArray->fetch_assoc()) {
$tmpReservationDetails = array();
$tmpReservationDetails["ItemID"] = $reservationDetail["ItemID"];
$tmpReservationDetails["Quantity"] = $reservationDetail["Quantity"];
$tmpReservationDetails["SubTotal"] = $reservationDetail["SubTotal"];
array_push($tmpReservation["Details"], $tmpReservationDetails);
}
array_push($response["reservations"], $tmpReservation);
}
$dbHandler->disconnect();
echoResponse(200, $response);
});
The JSON is displayed as..
{
"ID": 5,
"UserName": "Coca Cola",
"NoOfPeople": 2,
"DateOfReservation": "1.79",
"TimOfReservation": null,
"Status": null,
"TotalAmount": null,
"SpecialRequirement": 0,
"Details": [
{
"ID": 1,
"ItemID": 3,
"Quantity": 2,
"SubTotal": ""
},
{
"ID": 2,
"ItemID": 4,
"Quantity": 2,
"SubTotal": 1.2
}
]
}
For example I can display the reservation status using the $reservation ["Status"] but I don't seem to know how to get any of the fields from
"Details": [
{
"ID": 1,
"ItemID": 3,
"Quantity": 2,
"SubTotal": ""
},
Here is the PHP code..
<?php
include ('libs\WsURLs.php');
include ('libs\WsConsumer.php');
$wsConsumer = new WsConsumer ();
$_POST = array ();
$result = $wsConsumer->executeGET ( GET_RESERVATION );
$reservations = $result ["reservations"];
// Populating the table
foreach ( $reservations as $reservation) {
echo ('<tr>');
echo ('<td>' . $reservation ["Status"] . '</td>');
echo ('</tr>');
?>
$reservation["Details"] is an array, you access the array elements:
$reservation["Details"][$i]["ItemID"]
is the Item ID of the i'th item in the reservation.
You can loop through the reservation details
foreach($reservation ["Details"] as $key=>value)
See this example you can go through the array and extract the values:
<?php
$json = '{
"ID": 5,
"UserName": "Coca Cola",
"NoOfPeople": 2,
"DateOfReservation": "1.79",
"TimOfReservation": null,
"Status": null,
"TotalAmount": null,
"SpecialRequirement": 0,
"Details": [
{
"ID": 1,
"ItemID": 3,
"Quantity": 2,
"SubTotal": ""
},
{
"ID": 2,
"ItemID": 4,
"Quantity": 2,
"SubTotal": 1.2
}
]
}';
$data = json_decode($json, true);
for($i = 0; $i < count($data['Details']); $i++) {
echo '<p>';
foreach($data['Details'][$i] as $key => $value) {
echo $key . ' -> ' . $value . '<br>';
}
echo '</p>';
}
In your case you can do that:
$id_search = 2;
foreach ( $reservations as $reservation) {
for($i = 0; $i < count($reservation['Details']); $i++) {
if($id_search == $reservation['Details'][$i]['ID']) {
echo '<p>';
foreach($reservation['Details'][$i] as $key => $value) {
echo $key . ' -> ' . $value . '<br>';
}
echo '</p>';
}
}
}

Getting information out a json sting

I am attempting to work with JSON in PHP and I was wondering if someone could help me out getting me to the $events=>$url when the information is returned from json_decode. What is the variable path. There are a number of looping record in the return data and I am using something like:
$data = json_decode($feeds,true);
foreach($data as $item=>$events) {
$date = $events=>$month.'/'.$events=>$day.'/'.$events=>$year;
$events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$item["title"].'</span><br />'.$item["details"].'</li>';
}
Here is the JSON sample (yes, I know it is incomplete)
{
"month": 5,
"year": 2013,
"events": [
{
"url": "http://www.engin.umich.edu/college/about/cal/events/2013/may/shavuot-ends",
"id": "shavuot-ends",
"month": 5,
"year": 2013,
"day": 16,
"startTime": "1:42",
"endTime": "1:42",
"hideTime": "true",
"deadline": "true",
"am_pm": "pm",
"am_pm_start": "pm",
"am_pm_end": "pm",
"title": "Shavuot ends",
"location": "",
"details": "Shavuot runs from May 14 to May 16.",
"host": "Michigan Engineering",
"event_type": "Holiday",
"image": {
"src": "http://www.engin.umich.edu/++resource++umich_images/default_event.jpg",
"alt": "Shavuot ends"
}
},...
You have mixed up your -> and => operators. Try like this:
$data = json_decode($feeds,true);
foreach($data['events'] as $event) {
$date = $event['month'].'/'.$event['day'].'/'.$event['year'];
$events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$event["title"].'</span><br />'.$event["details"].'</li>';
}
$data['events']['url']
The array is multidimensional.
foreach($data as $key=>$item) {
if($key=='events') {
$url = $item['url'];
}
}
or
foreach($data['events'] as $key=>$item) {
if($key=='url') {
$url = $item;
}
}
try this:
$data = json_decode($feeds);
$eventsHtml = "";
foreach($data->events as $event ) {
$date = $data->month.'/'.$event->day.'/'.$data=>year;
$eventsHtml .='<li><span class="engindate">'.$date.
'</span><br /><span class="source">'.
$event=>title.
'</span><br /><a href="'.$event=>url.'">'.
$event->details.'</a></li>';
}
You have an object "data". This has a member "month", so this is $data->month
It has a member "events" which is an array. The first event is $data->events[0]. If you iterate with a foreach, this is foreach($data->events as $event ) { having $event as the one event.
Basic errors:
$events=>$month // is inproper syntax
foreach($data as $item=>$events) {
..
$events.= // this would overwrite the iterator variable above ??

Categories