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
)
Related
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
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)
I am trying to handle a situation with a nested multiple array that is received in PHP by $_POST from Javascript-Jquery (as Object not as Json)
. The nested Object looks like this:
{
"Videotheck":{
{
"Category":"Comedy",
"Title_Liste":[
{
"Title":"Millers",
"Year":"2014"
},
{
"Title":"Yogi",
"Year":"2012"
}
]
},
{
"Category":"Action",
"Title_Liste":[
{
"Title":"Rodulf",
"Year":"2014"
},
{
"Title":"Matrix",
"Year":"2000"
}
]
}
}
}
And now the information in this Object need to be splited. For example the title list of each category should be stored in a var
$comedy_title_liste = [];
$action_title_liste = [];
I tryed this:
if($_POST){
$arr1 = $_POST['Videotheck'];
foreach($arr1 as $vtk){
foreach($vtk as $data => $v){
foreach($v as $key => $value){
foreach($value as $k => $info){
echo $k.' '. $info;
}
}
}
}
}
Like this I can get only all title list from all categories, but is necessary to get for each category the list of titles separeted. I don't know really how to handle the situation.
Well this is what I have. I guest that there is something not correct.
Not 100% exact but you can give a try :
$result = array();
$parent = $_POST['Videotheck'];
foreach($parent as $key=> $child) {
$result[$child['Category']."_title_liste"] = array();
foreach($child['Title_Liste'] as $cKey => $val) {
$result[$child['Category']."_title_liste"][] = $val['Title'];
}
}
I have this
{
"items":[
{
"id":463282624,
"original_id":463282624,
"defindex":10175,
"level":1,
"quality":4,
"inventory":2147483980,
"quantity":1,
"attributes":[
{
"defindex":187,
"value":1106771968,
"float_value":31
}
]
},
{
"id":465686099,
"original_id":465686099,
"defindex":10175,
"level":1,
"quality":4,
"inventory":2147483979,
"quantity":1,
"attributes":[
{
"defindex":187,
"value":1106771968,
"float_value":31
}
]
}
]
}
How can i take out the ['id'] of the item with ['defindex'] = 10175
Please help!
PHP doesn't provide any way to retrieve elements by the contents, so you have to write a loop:
foreach ($object['items'] as $item) {
if ($item['defindex'] == 10175) {
$id = $item['id'];
break;
}
}
If you're going to need to do this repeatedly, you should transform your data into an associative array that uses defindex as the key, then you can access them easily.
$items_by_defindex = array();
foreach ($object['items'] as $item) {
$items_by_defindex[$item['defindex']] = $item;
}
$id = $items_by_defindex[10175];
I have a json feed that is more or less a list of objects
each has it's own id and idParent. objects that have idParent of null are the base parent elements. What I'm trying to achieve is to make a proper multidimensional array like a tree view. Keep in mind that children can have children too.
{
"obj1":{
"idParent":null,
"id":"parent1"
},
"obj2":{
"idParent":null,
"id":"parent2"
},
"obj3":{
"idParent":null,
"id":"parent3"
},
"obj4":{
"idParent":null,
"id":"parent4"
},
"obj5":{
"idParent":null,
"id":"parent5"
},
"obj6":{
"idParent":"parent1",
"id":"layer1-1"
},
"obj7":{
"idParent":"parent1",
"id":"layer1-2"
},
"obj8":{
"idParent":"parent2",
"id":"layer1-3"
},
"obj9":{
"idParent":"parent4",
"id":"layer1-4"
},
"obj10":{
"idParent":"parent3",
"id":"layer1-5"
},
"obj11":{
"idParent":"layer1-1",
"id":"layer2-1"
},
"obj12":{
"idParent":"parent5",
"id":"layer2-2"
},
"obj13":{
"idParent":"layer1-4",
"id":"layer2-3"
},
"obj14":{
"idParent":"layer1-5",
"id":"layer2-4"
},
"obj15":{
"idParent":"layer1-5",
"id":"layer2-5"
}
}
I've managed to filter out the root parents but after that I fail very bad
The first function does filter out the root parent nodes with idParent of null.
function decodeData($data) {
global $out;
foreach ($data as $key => $obj) {
if (is_array($obj)) {
foreach ($obj as $prop => $value) {
if ($prop == 'idParent') {
if($value == null) {
array_push($out, $obj);
unset($data[$key]);
}
}
}
}
}
if (count($data) > 0) {
decodeData($data);
} else {
echo json_encode(array('length'=>count($data)));
}
}
And this is what I'm experimenting on with no result
function decodeData($arrays) {
global $out;
foreach ($arrays as $array_name => $arr) {
foreach ($arr as $arr_prop => $arr_val) {
if ($arr_prop == 'idParent' && $arr_val == null) { // we found root parents
array_push($out, $arr);
unset($arrays[$array_name]); //remove array from the list
} else { // check if idParent is inside out
foreach ($out as $out_arr_name => $out_arr) { // iterate through out arrays
foreach ($out_arr as $out_arr_prop => $out_prop_val) { //
if ($out_arr_prop == 'id' && $arr_prop == 'idParent' && $out_arr_val == $arr_val) {
array_push($out_arr['children'], $obj);
unset($arrays[$array_name]);
}
}
}
}
}
}
if (count($arrays) > 0) {
decodeData($arrays);
} else {
echo json_encode(array('length'=>count($arrays)));
}
}
If anyone could provide some help I would really appreciate it.
I couldn't figure out what output do you want, so I just made a simple tree structure:
$data = json_decode( $your_json_string );
// Store each element in a lookup table indexed by element id
// 0th pass: put a fake root element there
$by_id = array(
'*' => new stdclass
);
// First pass: put each element into there
foreach( $data as $o ) $by_id[ $o->id ] = $o;
// Second pass: add each element into its parent's children array
foreach( $data as $o ){
$pid = $o->idParent ? $o->idParent : '*';
$p = $by_id[ $pid ];
$p->children[] = $o;
}
// Trash everything else, we start from the (fake) root element:
$tree = $by_id['*']->children;
/**** REVERSE ****/
$todo = $tree;
$json = array();
while( $todo ){
$o = array_shift( $todo );
if( isset( $o->children )){
$todo = array_merge( $todo, $o->children );
unset( $o->children );
}
$json[] = $o;
};
echo json_encode( $json );
The result:
http://codepad.viper-7.com/V7PjDh