Parse JSON on PHP and extract the particular value(s) - php

Objective: To parse following json string and get mentioned values separately, later those separated values are going to be inserted to mysql database. I have checked my json string on JsonLint
user_name,
selected_date,
selected_project,
tasks , 4.1.task_name, 4.2 work_hours
{
"user_name": "USER",
"selected_date": "2015-06-08",
"selected_project": "Project1",
"tasks": [
{
"task_name": "task-1",
"work_hours": [
{
"Monday": " 3"
},
{
"Tuesday": " 0"
},
{
"Wednesday": " 2.5"
},
{
"Thursday": " 2"
},
{
"Friday": " 0"
},
{
"Saturday": " 0"
},
{
"Sunday": " 0"
}
]
}
]
}
PHP code is:
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($response, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val)
{
if(is_array($val))
{
echo "$key:\n";
}
else
{
echo "$key => $val\n";
echo "$value";
}
}
As i am new to JSON and PHP, i could not solve this, help would be appreciated.

<?
$json = '{
"user_name": "USER",
"selected_date": "2015-06-08",
"selected_project": "Project1",
"tasks": [
{
"task_name": "task-1",
"work_hours": [
{
"Monday": " 3"
},
{
"Tuesday": " 0"
},
{
"Wednesday": " 2.5"
},
{
"Thursday": " 2"
},
{
"Friday": " 0"
},
{
"Saturday": " 0"
},
{
"Sunday": " 0"
}
]
}
]
}';
// decode your json into associative arrays
$decoded = json_decode($json, true);
// use array
echo "Username: ". $decoded['user_name'] . "<br>";
echo "Date: ". $decoded['selected_date'] . "<br>";
echo "project: ". $decoded['selected_project'] . "<br>";
echo "Task: ". $decoded['tasks'][0]['task_name'] . "<br>";
foreach($decoded['tasks'][0]['work_hours'] as $key => $value) {
foreach($value as $key2 => $value2){
echo $key2 . ": ". $value2 . "<br>";
}
}
?>

Related

php ms sql server stored procedure return json string max 2034

PHP reads just 2034 characters from the returned JSON string value from stored procedure "sp_test". Why just 2034 characters and not more?
Using PHP Version 5.6.31 with SQL Express 2017
$query = "EXEC sp_test";
$stmt = sqlsrv_prepare($GLOBALS['connIntern'], $query);
if (!sqlsrv_execute($stmt)) {
if (($errors = sqlsrv_errors() ) != null) {
foreach ($errors as $error) {
echo "SQLSTATE: " . $error['SQLSTATE'] . "<br />";
echo "code: " . $error['code'] . "<br />";
echo "message: " . $error['message'] . "<br />";
}
}
die;
}
$array = [];
if (!empty($result)) {
while ($row = sqlsrv_fetch_array($result)) {
array_push($array, $row[0]);
}
}
return $array;
Stored Procedure "sp_test":
SELECT [Tracking].[orderNumber],[Tracking].[tcpState], [Stations].[startdate],[Stations].[enddate],[Stations].[tcpState],[Stations].[name]
FROM [Tracking]
LEFT JOIN [Stations] ON [Tracking].[orderNumber] = [Stations][orderNumber]
FOR JSON AUTO
Formatted result:
[
{
"orderNumber": 123455,
"tcpState": 3,
"Stations": [
{
"startdate": "2011-05-06",
"enddate": "2012-09-15",
"tcpState": 3,
"name": "Roger"
},
{
"startdate": "2011-02-06",
"enddate": "2012-05-15",
"tcpState": 4,
"name": "Hans"
}
]
},
{
"orderNumber": 1566,
"tcpState": 3,
"Stations": [
{
"startdate": "2011-06-06",
"enddate": "2012-08-15",
"tcpState": "6",
"name": "Mike"
},
{
"startdate": "2011-03-06",
"enddate": "2012-03-15",
"tcpState": "6",
"name": "Tom"
}
]
}
]
Found the issue
if (!empty($result)) {
while ($row = sqlsrv_fetch_array($result)) {
array_push($array, $row[0]);
}
I thought i get the whole string in one row but i have to merge it.Like this:
if (!empty($result)) {
while ($row = sqlsrv_fetch_array($result)) {
array_push($array, $row);
}
}
if(count($array) > 0){
foreach ($array as $json){
$jsonPiece = $json[0];
$jsonString .= $jsonPiece;
}
}
For PDO-driver use this :
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_NUM); // array
$jsonString=""; // final JSON-string
foreach ($result as $row) {
$jsonString .=$row[0];
}

Select individual column json in php

{
"responseData": {
"results": [
{
"title": "sobig",
"titleNoFormatting": "test",
},
{
"title": "test 2 ",
"titleNoFormatting": "test 2sd",
},
{
"title": "asdasdasda",
"titleNoFormatting": "asdasdasd",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
.
.
.
.
{
"title": "last thing",
"titleNoFormatting": "sada",
}
],
I have json files like this.
for($i=$veri1; $i <= $veri2; $i++) {
$uri = "http://test.com/json/".$i."/0";
$json = json_decode(file_get_contents($uri));
if($json->data->price >= $nakit && $json->data->odds >= $oran)
{
I'm getting some data with this code correctly from another json file.
i want get data from first json code, if "title" == "sobig" . How can I do that.
$json->responseData->results->title == sobig is not working. How can I get data if title is sobig
$json= json_decode($response, true);
foreach ($json['responseData']['results'] as $key => $value) {
if ($value == 'sobig') {
// found it
}
}
Try this example to see if this may fix your issue.
<?php
$json = '{ "responseData": {
"result" : [
{ "title": "sobig" , "titleNo":"test"},
{ "title": "loco" , "titleNo":"test"},
{ "title": "tom" , "titleNo":"test"}
]
}}';
$jsonDecoded = json_decode($json);
foreach ($jsonDecoded->responseData->result as $key => $value) {
var_dump($value); echo '<br>';
if($value->title == 'sobig'){
echo "we did it!!";
echo "<br>";
}
}
?>
I place a couple of var dumps so you can see the stucture of your object and why you need to use the foreach

Accessing data in a multidimensional JSON object

I have the following JSON object returned from an API call in the $result variable, and my problem is that I need to access the "name" item in each list, but it doesn't work
{
"status": "success",
"data": {
"lists": [
{
"id": "0032",
"name": "Stan",
"status": "active",
},
{
"id": "0043",
"name": "David",
"status": "active",
},
{
"id": "2323",
"name": "Robert",
"status": "pending",
}
]
}
}
Code :
if (isset($result)) {
$json_object = json_decode($result, true);
echo $json_object['status'];
echo $result;
if ($json_object['status'] == 'success') {
$json_object2 = $json_object['data'];
foreach ($json_object['data'] as $key => $value){
foreach ($value as $key2 => $value2){
echo $key2 . " : " . $value2 . "</br>";
}
}
} else {
echo $json_object['data'];
}
}
Try something like this
<?php
$result = '{"status":"success","data":{"lists":[{"id":"0032","name":"Stan","status":"active"},{"id":"0043","name":"David","status":"active"},{"id":"2323","name":"Robert","status":"pending"}]}}';
$json_object = json_decode($result, true);
foreach($json_object['data']['lists'] as $item)
{
echo $item['name']."<br>";
}
?>

json-php giving filed out put two times?

There is records about the login_ids in json array. I want to fetch required results in json-php decode function. It is giving the login_id two times on top and bottom for each row. I there any way not to print the login_id in the value filed? The code details are given below.
<?php
$json = '{"records" :
[
{
"Name": "Jhon",
"Age": "45",
"Place": "Kettle",
"Phone": "9834453",
"log_id": "216"
},
{
"Name": "Bill",
"Age": "41",
"Place": "Ottava",
"Phone": "4513453",
"log_id": "215"
},
{
"Name": "James",
"Age": "39",
"Place": "Mexico",
"Phone": "3456734",
"log_id": "217"
},
{
"Name": "larry",
"Age": "51",
"Place": "New city",
"Phone": "34890453",
"log_id": "213"
}
]
}';
$myjson = json_decode($json, true); // decode the json string to an array
foreach ( $myjson['records'] as $row ) { // loop the records
echo 'Details of login id: '. $row['log_id']. '<br/>';
foreach ( $row as $field => $value ) { // loop the fields
echo $field . ': '. $value . '<br>';
}
echo '<br/>';
}
?>
Also is there any simple method to print the required login id (i.e where the login_id="217") so that the address of one person is given out put.
Following code my be better but not tested.
foreach ( $myjson['records'] as $row ) {
if ($row['log_id'] =='216') { // login id to be checked
echo 'Details of login id: '. $row['log_id']. '<br/>';
foreach ( $row as $field => $value ) { // loop the fields
if ($field != "log_id") { // hide the login id t bottom
echo $field . ': ' . $value . '<br>';
}
}
echo '<br/>';
}
}
Test the field name before printing it.
foreach ($row as $field => $value {
if ($field != "log_id") {
echo $field . ': ' . $value . '<br>';
}
}

Parsing JSON array with PHP foreach

Wondering why my PHP code will not display all "Value" of "Values" in the JSON data:
$user = json_decode(file_get_contents($analytics));
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
}
foreach($user->data->values as $values)
{
echo $values->value . "\n";
}
The first foreach works fine, but the second throws an error.
{
"data": [
{
"id": "MY_ID/insights/page_views_login_unique/day",
"name": "page_views_login_unique",
"period": "day",
"values": [
{
"value": 1,
"end_time": "2012-05-01T07:00:00+0000"
},
{
"value": 6,
"end_time": "2012-05-02T07:00:00+0000"
},
{
"value": 5,
"end_time": "2012-05-03T07:00:00+0000"
}, ...
You maybe wanted to do the following:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
You need to tell it which index in data to use, or double loop through all.
E.g., to get the values in the 4th index in the outside array.:
foreach($user->data[3]->values as $values)
{
echo $values->value . "\n";
}
To go through all:
foreach($user->data as $mydata)
{
foreach($mydata->values as $values) {
echo $values->value . "\n";
}
}
$user->data is an array of objects. Each element in the array has a name and value property (as well as others).
Try putting the 2nd foreach inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}

Categories