Hello i have a json array which contains an array structure. I am trying to fetch the value against a particular key. Like getting a key with name lower and value 9226. I have implemented for each loop but i cannot get into it. There is some issue in my comparison statement.
{
"tax_structure": [
{
"tax_data": {
"lower": 0,
"upper": 9225,
"tax_rate": 10,
"amount": 0
}
},
{
"tax_data": {
"lower": 9226,
"upper": 37450,
"tax_rate": 15,
"amount": 922.50
}
}
]
}
Php file:
<?php
$expense=10000;
$str_data = file_get_contents("data.json");
$data = json_decode($str_data,true);
foreach ($data["tax_structure"] as $tax_data) {
foreach ($tax_data["tax_data"] as $key => $value) {
if($key=="lower" && $expense>$value) & ($key=="upper" &&$expense<$value)
{
//do something if expenses value falls between the lower and upper limit values of keys
}
}
}
?>
I believe you are looking for something like the following.
There is no need for the second for loop.
$expense = 10000;
$str_data = file_get_contents("data.json");
$data = json_decode($str_data,true);
foreach ($data["tax_structure"] as $tax_data_object) {
if($tax_data_object['tax_data']['lower'] < $expense && $tax_data_object['tax_data']['upper'] > $expense){
// Do stuff
}
}
EDIT
You should try print_r($data);. This will show the structure of your data array.
If you examine the structure of your data the above code should be obvious.
If it isn't, here are a few sources for further learning:
PHP: Arrays
JSON introduction
<?php
$expense = 10000;
$str_data = file_get_contents("data.json");
$data = json_decode($str_data, true);
foreach ($data["tax_structure"] as $tax_data) {
foreach ($tax_data["tax_data"] as $key => $value) {
if ($key == "lower" && $expense > $value) {
echo "Key is lower and the value is " . $value . "<br>";
}
if ($key == "upper" && $expense < $value) {
echo "Key is upper and the value is " . $value . "<br>";
}
}
}
?>
You cant do this if($key=="lower" && $expense>$value) & ($key=="upper" &&$expense<$value)
Related
Trying to read a json file and assign values to php variables.
My json file looks like this:
{
"123456": {
"fuelpump": {
"name": "Pump XX",
"address": "Address here",
"8493024" <-- I WANT THIS THE VALUE 8493024: {
"connectors": {
"8493024-1": {
"infohere": "more info here"
}
}
}
}
},
"456789": {
"fuelpump": {
"name": "Pump YY",
"address": "Address here",
"8374769" <-- I WANT THIS THE VALUE 8374769: {
"connectors": {
"8374769-1": {
"infohere": "more info here"
}
}
}
}
}
}
This is how my php code is looking:
<?php
$jsonfile = file_get_contents('jsonfile.json');
$jsonitems = json_decode($jsonfile);
foreach ($jsonitems as $location) {
$name = $location->fuelpump->name; //This works OK
$address = $location->fuelpump->address; // This ALSO OK
$fuelPumpno = $location->fuelpump[2]; //This doesnt work. Here i want the key names 8493024 and 8374769
}
How can i get the name of the keys "8493024" and "8374769"?
You have to loop over the fuelpump properties to find the value.
If that is the structure of the json object, and it does not change, you can do with this:
foreach ($location->fuelpump as $key => $value) {
if ($key !== 'name' && $key !== 'address') {
$fuelPumpno = $key;
}
}
Another way
it filters the keys of the $location object and get the first element of the result:
$fuelPumpno = current(array_filter(array_keys(get_object_vars($location->fuelpump)), function($el) {
return $el !== 'name' && $el !== 'address';
}));
Another approach is to filter only numeric values:
$jsonfile = file_get_contents('jsonfile.json');
$jsonitems = json_decode($jsonfile, true);
$pumpNo = [];
foreach ($jsonitems as $data) {
$pumpNo = array_merge($pumpNo, array_filter(array_keys($data["fuelpump"]), 'is_numeric'));
}
print_r($pumpNo);
It returns
Array
(
[0] => 8493024
[1] => 8374769
)
I want to select the "RSI" from the first element only.
Array (json file):
{
"Technical": {
"2019-01-11 15:30": {
"RSI": "123"
},
"2019-01-11 14:30": {
"RSI": "456"
}
"2019-01-11 14:30": {
"RSI": "789"
}
}
My php:
foreach ($json['Technical'] as $field => $value) {
echo $value['RSI']; // Gives 123456789
}
I want only 123
I tried:
echo $value[0]['RSI']; // Gives NULL
Break the loop with break; and it will only return the first item.
foreach ($json['Technical'] as $field => $value) {
echo $value['RSI']; // Gives 123
break;
}
If you want specific items then use a "$key" variable.
$key = 0;
foreach ($json['Technical'] as $field => $value) {
if($key == 0 || $key ==1){
echo $value['RSI'];
}
$key++;
}
// 123456
Change the if to suit your needs.
I need to modify the data structure of json array list as per some key value using PHP. I am explaining my code below.
<?php
$output=array(
array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA001"
),array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA002"
),array(
"first_name"=>"Rama",
"last_name"=>"Nayidu",
"reg_no"=>13,
"paper_code"=>"BA001"
)
);
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$result[]=array(
"name"=>$value["first_name"].' '.$value['last_name'],
"reg_no"=>$value['reg_no'],
"paper1"=>$value['paper_code'],
"paper2"=>"",
"paper3"=>"",
"paper4"=>""
);
}
}
The output of the input array is given below.
// Output:
[
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA001"
},
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA002"
},
{
"first_name":"Rama",
"last_name":"Nayidu",
"reg_no":13,
"paper_code":"BA001"
}
];
The above is my array list. Here I need to modify the all row value by reg_no means if there are multiple rows including same reg_no then those will merge with joining the both name and my expected output should like below.
expected output:
[
{
'name':"robin sahoo",
"reg_no":12,
"paper1":"BA001",
"paper2":"BA002",
"paper3":"",
"paper4":""
},
{
'name':"Rama Nayidu",
"reg_no":13,
"paper1":"BA001",
"paper2":"",
"paper3":"",
"paper4":""
}
]
Here paper1,paper2,paper3,paper4 will be selected serially means suppose same reg_no=12 has first row paper_code= BA001 then it will be paper1=BA001 and second row paper_code=BA002 then it will be paper2=BA002 and so on. Here I am using PHP to map this array.
Try the following, Let me know..
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
$temp=array();
if(!empty($output)){
foreach ($output as $key => $value) {
if(isset($temp[$value['reg_no']])){
if(empty($temp[$value['reg_no']]["paper1"]) || $temp[$value['reg_no']]["paper1"] == ""){
$temp[$value['reg_no']]["paper1"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper2"]) || $temp[$value['reg_no']]["paper2"] == ""){
$temp[$value['reg_no']]["paper2"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper3"]) || $temp[$value['reg_no']]["paper3"] == ""){
$temp[$value['reg_no']]["paper3"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper4"]) || $temp[$value['reg_no']]["paper4"] == ""){
$temp[$value['reg_no']]["paper4"] = $value['paper_code'];
}
}else{
$temp[$value['reg_no']] = array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}
}
if(!empty($temp)){
foreach ($temp as $key => $value) {
$result[] = $value;
}
}
This Code May help you
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$output[$key]=array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}echo "<pre>";print_r($output);
?>
You can try with this
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'name' => $name,
'reg_no' => $value['reg_no'],
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'];
}
$result = array_values($result); // reindex result array
$result = json_encode($result); // Encode to json format
print_r($result); // print result
This assumes that first_name and last_name is always same for each reg_no
I am trying to loop through a JSON Array returning a unique date and all the tasks associated with that date.
This is an example of my JSON array:
<!-- language: lang-json -->
[
{
"task":"Clean my teeth",
"date":"today"
},
{
"task":"Jumping Jacks",
"date":"tomorrow"
},
{
"task":"Call Mom",
"date":"today"
},
{
"task":"Wash The Dog",
"date":"2017/03/01"
},
{
"task":"Clean The House",
"date":"today"
}
]
I want to display something like this:
Today
Clean my teeth
Call Mom
Tomorrow
Jumping Jacks
2017/03/01
Clean The House
Here is my function: I can get all the unique days but I'm not sure how to display the tasks associated with that day.
public static function Iteration()
{
$file = file_get_contents("newfile.php");
$result = rtrim( $file, ",");
$array = json_decode('[' . $result . ']');
$unique_dates = array();
$unique_tasks = array();
foreach($array as $item) {
if ( in_array($item->date, $unique_dates) ) {
continue;
}
$unique_dates[] = $item->date;
$time = strtotime($item->date);
$newformat = date('Y-m-d',$time);
echo '<h2>' . $newformat . '</h2>';
echo $item->task;
}
}
You can traverse the JSON list, and keep the unique records and store tasks at the same traversal.
By using the isset(), you can determine whether the key is unique or not.
Try this:
<?php
$json = '[{"task": "Clean my teeth","date": "today"},{"task": "Jumping Jacks","date": "tomorrow"},{"task": "Call Mom","date": "today"},{"task": "Wash The Dog","date": "2017/03/01"},{"task": "Clean The House","date": "today"}]';
$array = json_decode($json);
$res = array();
foreach ($array as $each) {
if (isset($res[$each->date]))
array_push($res[$each->date], $each->task);
else
$res[$each->date] = array($each->task);
}
foreach ($res as $date => $tasks){
echo "<h3>{$date}</h3>";
foreach ($tasks as $task)
echo "<p>$task</p>";
}
I have to display team points under respective team name
I have following json data
{
"id":319231,
"innings":[
{"id":967766},
{"id":967767},
{"id":967768},
{"id":967769}
],
"team1":{
"team":{"name":"Minor Counties","id":115104,"club":{"name":"Minor Counties","id":98110}},
"innings":[
{"id":967766,"points":253,"wickets":10,"overs":86,"balls":4},
{"id":967768,"points":190,"wickets":5,"overs":61,"balls":0}
]
},
"team2":{
"team":{"name":"Major Counties","id":93648,"club":{"name":"Major Counties","id":35487}},
"innings":[
{"id":967767,"points":229,"wickets":10,"overs":67,"balls":4},
{"id":967769,"points":64,"wickets":4,"overs":23,"balls":2}
]
},
}
Now I want result like :
Minor Counties Major Counties
253/10 & 190/5 229/10 & 64/4
Currently I am getting result like :
Minor Counties Minor Counties Major Counties Major Counties
253/10 190/5 229/10 64/4
Here is my php code so far :
$team1 = $read_json->team->team1->name;
$team2 = $read_json->team->team2->name;
foreach($read_json->team1->innings as $team1Innings){
$points = $team1Innings->points;
$wickets = $team1Innings->wickets;
$overs = $team1Innings->overs;
$balls = $team1Innings->balls;
echo "<div class=\"score-total\"><span class=\"score-team\">$team1</span>$points/$wickets<span class=\"score-overs\">$overs.$balls overs</span></div>";
}
similar code to get team2 points
$json = '{
"id":319231,
"innings":[
{
"id":967766
},
{
"id":967767
},
{
"id":967768
},
{
"id":967769
}
],
"team1":{
"team":{
"name":"Minor Counties",
"id":115104,
"club":{
"name":"Minor Counties",
"id":98110
}
},
"innings":[
{
"id":967766,
"points":253,
"wickets":10,
"overs":86,
"balls":4
},
{
"id":967768,
"points":190,
"wickets":5,
"overs":61,
"balls":0
}
]
},
"team2":{
"team":{
"name":"Major Counties",
"id":93648,
"club":{
"name":"Major Counties",
"id":35487
}
},
"innings":[
{
"id":967767,
"points":229,
"wickets":10,
"overs":67,
"balls":4
},
{
"id":967769,
"points":64,
"wickets":4,
"overs":23,
"balls":2
}
]
}
}';
$items = json_decode($json);
unset($items->id);
unset($items->innings);
foreach ($items as $item) {
echo "<b>{$item->team->name}</b>";
$innings = [];
foreach ($item->innings as $inning) {
$innings[] = "{$inning->points} / {$inning->wickets}";
}
echo '<br>';
echo implode(' & ', $innings);
echo '<br>';
}
Use json_decode() with true as second parameter it gives you an associative array and it will convert the JSON object into a PHP object.It will make your life easier.
Try this :
$jsonObj = json_decode($json,true);
$inningsPoint = [];
foreach ($jsonObj as $teamData) {
if(!empty($teamData[team][name])) {
echo $teamData[team][name].'<br>';
$inningsPoint = [];
}
foreach ($teamData[innings] as $inningsData) {
$inningsPoint[] = "$inningsData[points] / $inningsData[wickets]";
}
echo implode(' & ', $inningsPoint);
}
Demo!
<?php
function showteams_results($k1,$points){
switch ($k1) {
case 'team1':
foreach ($points as $key => $value) {
if($key=="team1")
{
echo ucfirst($key)."<br>";
foreach ($value as $k => $v) {
echo "Innings".$v."<br>";
}
}
}
break;
case 'team2':
foreach ($points as $key => $value) {
if($key=="team2")
{
echo ucfirst($key)."<br>";
foreach ($value as $k => $v) {
echo "Innings".$v."<br>";
}
}
}
break;
default:
echo "Team no points!";
break;
}
}
$points=array();
$jsonObj = json_decode($json,true);
$inningsPoint = [];
foreach ($jsonObj as $k1 => $teamData) {
//extracting points of team1---------->
if($k1=="team1"){
//showteams_results($k,$jsonObj);
foreach ($teamData as $k => $v) {
if($k=="innings")
{
foreach ($v as $k => $vf) {
foreach ($vf as $k => $vk) {
if($k=="points")
$points["team1"][]=$vk;
}
}
}
}
//sending data teams
showteams_results($k1,$points);
}
//extracting points of team2---------->
if($k1=="team2"){
//showteams_results($k,$jsonObj);
foreach ($teamData as $k => $v) {
if($k=="innings")
{
foreach ($v as $k => $vf) {
foreach ($vf as $k => $vk) {
if($k=="points")
$points["team2"][]=$vk;
}
}
}
}
//sending data teams
showteams_results($k1,$points);
}
}
?>