extract php array value - php

I have the following array (exposed using var_dump).
array (size=3)
'auth' => string 'debug' (length=5)
'url' => string 'http://X.X.X.X/status.cgi?' (length=31)
'page' => string '{ "host": { "uptime": 1543, "time": "2011-07-26 12:07:40", "fwversion": "v1.1.1", "hostname": "ASDASDASD", "netrole": "DFDFDF" }, "lan": { "status": [{ "plugged": 1, "speed": 100, "duplex": 1 }], "hwaddr": "00:00:22:11:11:11", "ip": "", "rx": { "bytes": 5988, "packets": 83, "errors": 0 }, "tx": { "bytes": 9496, "packets": 120, "errors": 0 } }, "wan": { "status": [], "hwaddr": "00:00:00:00:00:00", "ip": "", "rx": { "bytes": 0, "packets": 0, "errors": 0 }, "tx": { "bytes": 0, "packets"'... (length=1779)
I need to extract info from WAN like ip or rx...
I have tried using $array['page']['wan']['rx'] but nothing!!!
Thanks.

The page value of your $array is not actually an array, but a string. Since it's a JSON string, you should use json_decode to decode the string into a meaningful format for PHP to handle:
$page = json_decode($array['page']);
$pageArray = json_decode($array['page']); // Returned as an array
And to get the RX for example:
var_dump($page->wan->rx); // Returned as an object
var_dump($pageArray['wan']['rx']); // Return as an array

Related

Trying to get property name and id of laravel payload

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

How to search recursively by key of a multi-dim array?

I am trying to create a recursive function that takes an array and looks for a property name children, and constructs an array out of the matching one.
This is not straight forward because I don't know which block of my JSON data will contain the key children, so I decided to write a recursive function.
I've tried
$testDataJson = '
{
"macAddress": "10:20:30:40:50:81",
"type": "HGW",
"children": [{
"macAddress": "98:D6:D6:D8:FF:34",
"pendingMethods": false,
"lastSeen": "2017-05-24T10:36:35",
"lastSeenLight": "GREEN",
"model": "AP7465CE-TN",
"type": "WIRELESS_ACCESS_POINT"
}, {
"macAddress": "44:66:E9:A1:2C:DC",
"pendingMethods": false,
"lastSeen": "2017-05-24T10:39:01",
"lastSeenLight": "GREEN",
"model": "PLC 200+ DIV -TN",
"type": "POWERLINE"
}, {
"macAddress": "D8:C2:A9:1C:44:47",
"pendingMethods": "False",
"lastSeen": "2017-05-24T10:39:01",
"lastSeenLight": "GREEN",
"model": "PG9073",
"type": "POWERLINE",
"children": [{
"macAddress": "22:CD:E6:8F:8C:B8",
"pendingMethods": false,
"lastSeen": "2017-05-24T10:38:16",
"lastSeenLight": "GREEN",
"model": "PG9073",
"type": "POWERLINE"
}, {
"macAddress": "13:E4:AB:33:36:AC",
"pendingMethods": false,
"lastSeen": "2017-05-24T10:29:13",
"lastSeenLight": "GREEN",
"model": "PG9072",
"type": "POWERLINE_WIRELESS_ACCESS_POINT"
}]
}]
}';
$testDataArray = json_decode($testDataJson,true);
function recursiveKeyFinder($array) {
$result = [];
if (!isset($array['children']) AND is_array($array)) {
return $result;
}else {
foreach($array['children'] as $child){
$result['macAddress'] = $child['macAddress'];
}
return recursiveKeyFinder($array);
}
}
var_dump(recursiveKeyFinder($testDataArray));
Result: Nothing from var_dump().
Desired result:
["macAddress": "98:D6:D6:D8:FF:34",
"macAddress": "44:66:E9:A1:2C:DC",
"macAddress": "D8:C2:A9:1C:44:47",
"macAddress": "22:CD:E6:8F:8C:B8",
"macAddress": "13:E4:AB:33:36:AC"]
How can I investigate this?
PHP already offers a specific tool for this operation: array_walk_recursive(); so there is no need to reinvent the wheel.
Your task can be swiftly, concisely completed with just one function call after preparing your json data.
Omitting the first macAddress (unwanted) value is done by passing only the subarray with the key of 'children' to array_walk_recursive().
Code: (Demo)
$array=json_decode($testDataJson,true)['children']; // this avoids including the first "non-children" macAddress value.
array_walk_recursive($array,function($v,$k)use(&$result){if($k==='macAddress') $result[]=$v;});
var_export($result);
Result:
array (
0 => '98:D6:D6:D8:FF:34',
1 => '44:66:E9:A1:2C:DC',
2 => 'D8:C2:A9:1C:44:47',
3 => '22:CD:E6:8F:8C:B8',
4 => '13:E4:AB:33:36:AC',
)
Alternatively, the input array can be prepared like this:
$array=array_diff_key(json_decode($testDataJson,true),['macAddress'=>'']);
This will ensure you don't accidentally grab any non-children macAddress values.
Like Barmar siad "You have infinite recursion."
This is my solution. It prints out all mac address
function recursiveKeyFinder($array) {
$result = [];
$result[] = $array['macAddress'];
if (isset($array['children'])) {
foreach($array['children'] as $child){
$result = array_merge($result,recursiveKeyFinder($child));
}
}
return $result;
}
Here the result
array (size=6)
0 => string '10:20:30:40:50:81' (length=17)
1 => string '98:D6:D6:D8:FF:34' (length=17)
2 => string '44:66:E9:A1:2C:DC' (length=17)
3 => string 'D8:C2:A9:1C:44:47' (length=17)
4 => string '22:CD:E6:8F:8C:B8' (length=17)
5 => string '13:E4:AB:33:36:AC' (length=17)
Hope this can help

Datatable Invalid JSON response error when my JSON is valid? PHP

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.

problem in getting JSON data through server?

I am using Tropo Web API, to get result from a chat application, i redirected my JSON response to my server side PHP file(http://myhost.in/vj/app3.php?tropo-engine=json), the JSON response is coming correctly but i am not able to fetch data from that using PHP,
the JSON response is as follows..
{
"result": {
"actions":
[
{
"attempts": 2,
"concept": "mumbai",
"confidence": 100,
"disposition": "SUCCESS",
"interpretation": "mumbai",
"name": "city",
"utterance": "mumbai",
"value": "mumbai",
"xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result grammar=\"1#6ac61bfd.vxmlgrammar\"><interpretation grammar=\"1#6ac61bfd.vxmlgrammar\" confidence=\"100\"><instance>mumbai<\/instance><input mode=\"voice\" confidence=\"100\" timestamp-start=\"1970-01-01T00:00:00.000\" timestamp-end=\"1970-01-01T00:00:00.000\">mumbai<extensions><word-confidence> 100 <\/word-confidence><\/extensions><\/input><extensions><probability> 0 <\/probability><nl-probability> 0 <\/nl-probability><necessary-word-confidence> 0 <\/necessary-word-confidence><\/extensions><\/interpretation><\/result>\r\n\r\n"
},
{
"attempts": 1,
"concept": "cricket",
"confidence": 100,
"disposition": "SUCCESS",
"interpretation": "cricket",
"name": "sports",
"utterance": "cricket",
"value": "cricket",
"xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result grammar=\"2#6ac61bfd.vxmlgrammar\"><interpretation grammar=\"2#6ac61bfd.vxmlgrammar\" confidence=\"100\"><instance>cricket<\/instance><input mode=\"voice\" confidence=\"100\" timestamp-start=\"1970-01-01T00:00:00.000\" timestamp-end=\"1970-01-01T00:00:00.000\">cricket<extensions><word-confidence> 100 <\/word-confidence><\/extensions><\/input><extensions><probability> 0 <\/probability><nl-probability> 0 <\/nl-probability><necessary-word-confidence> 0 <\/necessary-word-confidence><\/extensions><\/interpretation><\/result>\r\n\r\n"
}
],
"callId": "b546e03db1ccfd2f0e8c58d970539501",
"complete": true,
"error": null,
"sequence": 1,
"sessionDuration": 11,
"sessionId": "ed6abc73b9c434385ea8cd8004c9ed0c",
"state": "ANSWERED"
}
}
the PHP code that i am using...
$json = file_get_contents("php://input");
$result = json_decode($json);
$value =$result->result->actions->value;
but i am getting null in the variable $value. How will get the value for city and sports as well..??
It is because $result->result->actions is an array. Try $result->result->actions[0]->value

Categories