iterate through json_encode array in PHP - php

i'm having problem on how to iterate in the array in json_encode.
I do ajax POST, in where i have a looping code that do "array push" in jQuery, something like this:
$(this).closest('tr.header').nextUntil('.header').each(function(){
i++;
var forms="<form method='POST'>"+$(this).html()+'</form>';
data.push($(forms).serializeArray());
});
So when i pass this to my controller/ other page, i do this:
$dataList = json_encode($this->input->post("form"));
echo $dataList ;
And the output is:
[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]
I have tried to do :
foreach ($dataList as $data) {
echo $data . "\n";
}
But only give me error on foreach.
Thanks in advance.

Use json_decode()function to get your data as an array then foreach your data.
$a = '[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]';
echo '<pre>';
$res = json_decode($a, true);
$newArr = [];
foreach($res as $data => $val)
{
foreach($val as $key2 => $val2)
{
$newArr[] = $val2;
}
}
foreach($newArr as $key => $val)
{
echo 'Name = ' . $val['name'] . ' Values = ' . $val['value'] . '<br/>';
}

Just decode the string and loop through the created array.
<?php
$a = '[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]';
echo '<pre>';
$res = json_decode($a, true);
$newArr = array();
foreach($res as $data => $val)
{
foreach($val as $k=>$value){
$value=array_values($value);
echo 'Name => ' . $value[0] . ' Value => ' . $value[1] . '<br/>';
}
}
?>

for array output you need to decode it with json_decode()
here is sample code.
$encode_data = '[[{"name":"category_1", "values":"packages"},{"name":"PK_1", "values": "1"}],[{"name":"category_2", "value":"products"},{"name":"PK_2", "value": "3"}]]';
$dataAr = json_decode($encode_data , true);
foreach($dataAr as $data)
{
foreach($data as $value){
$value=array_values($value);
echo 'name => ' .$value[0] . ' value => ' .$value[1];
echo "<br>";
}
}

Related

PHP Parsing JSON to HTML Table multi dimensional arrays

I have the following JSON Data:
{
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "TimeGenerated",
"type": "datetime"
},
{
"name": "Computer",
"type": "string"
}
],
"rows": [
[
"2022-12-03T21:58:48.519866Z",
"DESKTOP-KAFCPRF"
],
[
"2022-12-03T21:58:48.5198773Z",
"DESKTOP-KAFCPRF"
]
]
}
]
}
I'm using this to and trying to find a way to parse the columns as tables headers(TH) and the row data as(TR).
This is what I have:
$jsonObjs = json_decode($data, true);
echo "<pre>" . var_dump($jsonObjs) . "</pre>";
foreach($jsonObjs as $a){
foreach($a[0] as $b) {
foreach($b[1] as $key => $value){
echo $key . " : " . $value . "<br />";
}
}
}
but my results are coming up like:
name : Computer
type : string
0 : 2022-12-03T21:58:48.5198773Z
1 : DESKTOP-KAFCPRF
Here is a loop that will go through the columns and rows. From here it's fairly simple to adjust the logic for building a table. If you need any further help, let me know.
foreach($jsonObjs["tables"] as $a)
{
// Columns
foreach($a["columns"] as $key => $value)
{
$cName = $value["name"];
$cType = $value["type"];
echo("Column name is: ".$cName);
echo("Column type is: ".$cType);
}
// Rows:
foreach($a["rows"] as $key => $value)
{
$rValue1 = $value[0];
$rValue2 = $value[1];
echo("Row: " . $rValue1 . " | " . $rValue2);
}
}

Trying to loop and display a JSON file with PHP

I have a JSON file that has an array inside. I want to loop inside each element of the JSON and display it. I can succesfully do it but I want when using the foreach loop refer to the field like this: $value["pessoa_id"];
When I'm doing like this I get it to display but after displaying it gets a message: "Notice: Undefined index: nome", like it was trying to access it again.
This is the JSON file:
{"Clientes": {
"Pessoa": [
{"pessoa_id" : 1, "nome": "INDUSTRIAL JAVARI LTDA", "endereco": "ENGENHO SANTA TERESA"},
{"pessoa_id" : 2, "nome": "AGROISA-AGRO IND. TRAVESSIA S/A", "endereco": "FAZENDA TRAVESSIA S/N"}
],
"Clientes": [
{"cliente_id" : 1, "loja" : 1, "cliente" : 1, "tpcli": "J", "pontoref": ""},
{"cliente_id" : 2, "loja" : 1, "cliente" : 2, "tpcli": "J", "pontoref": ""}
]
}
}
And the php code:
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key => $value){
foreach ($value as $key => $val){
foreach ($val as $key => $v){
echo $v["nome"] . " " . $v["endereco"];
echo "<br>";
}
}
}
I want to be able to in one foreach see if it's a "Pessoa" or "Clientes" and loop throught it by getting the fields by the name.
You also iterate over the 2nd array Clientes. You could access the array directly and only iterate over that data:
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
$pessoa = $json["Clientes"]["Pessoa"];
foreach ($pessoa as $key => $value){
echo $value["nome"] . " " . $value["endereco"];
echo "<br>";
}
Update:
If you need/want to loop over the whole data-set like you did in your question, you can check if you are in the correct element of the object and only than iterate and output the data.
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key1 => $value){
if ($key1 == "Clientes") {
foreach ($value as $key2 => $val){
if ($key2 == "Pessoa") {
foreach ($val as $key3 => $v){
echo $v["nome"] . " " . $v["endereco"];
echo "<br>";
}
}
}
}
}

Not able to parse nested Json array in PHP while print_r function is printing all values properly

I am trying to parse a json array string. Though print_r prints all the values properly but while fetching the records I failed.
I must be doing something very terribly wrong. Could you please help to correct it.
So here is my code
<?
$str ='
{
"tenant_view_details": [
{
"status":"S",
"tenant_general":[
{"tenant_id":"6003","code":"ICI001","type":"BANK","category":"SM","gstn":"IWSDFS7372","pan":"KSAH9876AS","cin":"ASHED456","name":"ICICI Bank","address_line_1":"23, Hertz Plaza, Rajiv Chowk","address_line_2":" ","address_city":"New Delhi","address_distict ":"New Delhi","address_state ":"DL","address_state_code ":"07","address_pin ":"119923","contact_name ":"contact_name","contact_phone ":"1234567890","contact_std_code ":"11","contact_landline ":"1234567890","contact_email_id ":"contact#email.com"} ],
"tenant_bank": [
{ "bank_name ":"xyz","bank_account_no ":"12345","account_type ":"abc","ifsc_code ":"xx123","address_line_1 ":"qwer","address_line_2 ":"23","address_city ":"abc","address_district ":"xyz","address_state_name ":"asd","address_state_code ":"02","address_pin ":"123456" } ],
"tenant_agreement": [
{ "category ":"OM","tenancy_type ":"EXT","echarge_type ":"FIX","total_tenancy_value ":"32900.00","energy_charge_value ":"16543.00","rev_share_pct ":"0.05","start_dt":"10-1-2018","end_dt":"31-12-2020","attachment_path ":"na","change_value ":"na","latest_flag ":"Y","w_status ":"20","status ":"ACT"} ],
"tenant_sites": [
{"tenant_id":"6003","site_master_id":"1020","tn_site_code":"UPWMORA00069473","tn_site_name":"Deendayal Nagar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1019","tn_site_code":"UPWGHAZ00069467","tn_site_name":"DJ College Newari Road, Modina","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1018","tn_site_code":"UPWMORA00069464","tn_site_name":"Bazar Makhbra","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1016","tn_site_code":"UPWGHAZ00069454","tn_site_name":"Hoshdarpur Garhi","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1011","tn_site_code":"UPWMUZN00069430","tn_site_name":"Sikanderpur","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1008","tn_site_code":"UPWALIG00069299","tn_site_name":"Mukund Vihar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"} ]
}
]
}
';
$dataset = json_decode($str, true);
//print_r ($dataset);
foreach ($dataset['tenant_view_details'] as $newdata) {
$general = $newdata['tenant_general'];
$bank = $newdata['tenant_bank'];
$agreement = $newdata['tenant_agreement'];
$sites = $newdata['tenant_sites'];
}
//prinitng data
echo "<br/>";
print_r($general);
echo "<br/>";
print_r($bank);
echo "<br/>";
print_r($agreement);
echo "<br/>";
foreach($general as $general_data){
(isset($general_data['tenant_id']) && !empty($general_data['tenant_id']))? $tenant_id=$general_data['tenant_id'] : $tenant_id="not set";
echo "<br/>tenant_id::" . $tenant_id;
}
foreach($bank as $bank_data){
(isset($bank_data['bank_name']) && !empty($bank_data['bank_name']))? $bank_name=$bank_data['bank_name'] : $bank_name="not set";
echo "<br/>bank_name:" . $bank_data['bank_name'];
}
foreach($agreement as $agreement_data){
(isset($agreement_data['category']) && !empty($agreement_data['category']))? $category=$agreement_data['category'] : $category="not set";
(isset($agreement_data['tenancy_type']) && !empty($agreement_data['tenancy_type']))? $tenancy_type=$agreement_data['tenancy_type'] : $tenancy_type="not set";
(isset($agreement_data['echarge_type']) && !empty($agreement_data['echarge_type']))? $echarge_type=$agreement_data['echarge_type'] : $echarge_type="not set";
echo "<br/>category:" . $category;
echo "<br/>tenancy_type:" . $tenancy_type;
echo "<br/>echarge_type:" . $echarge_type;
}
?>
Your problem is that in your $bank and $category arrays, all the keys have trailing spaces on them. If you change the references to include those spaces, your code works fine. See https://3v4l.org/GX5iC
Alternatively you can trim the array keys, using something like this code inside your foreach loops:
$bank_keys = array_map('trim', array_keys($bank_data));
$bank_data = array_combine($bank_keys, array_values($bank_data));
You could also create a recursive function to trim the entire $dataset value. For example:
function trim_keys($array) {
foreach ($array as $key => $value) {
echo "trimming key '$key' to '" . trim($key) . "'\n";
unset($array[$key]);
$array[trim($key)] = $value;
if (is_array($value))
$array[trim($key)] = trim_keys($value);
else
$array[trim($key)] = $value;
}
return $array;
}
Then, by using
$dataset = trim_keys($dataset);
Your code will work fine. Demo on 3v4l.org

PHP echo JSON nested array values

I want to echo all expanded_url and urls. echo $name prints results . echo $value doesn't print anything because of nested array. How do I echo all values?
$json ='{ "results" : [ { "entities" :
[ { "urls" : [ { "expanded_url" : "http://www.google.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.facebook.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.twitter.com",
"url" : "http://t.co/WZnUf68j"
} ] } ],
"from_user" : "A-user-name",
"from_user_id" : 457304735,
"text" : "Ich R U #BoysNoize #SuperRola"
} ] }';
# $json_array = (array)(json_decode($json));
$data = json_decode($json,true);
foreach($data as $name => $value){
echo $name.'<br>';
echo $value; // NOT WORKING - HOW TO ECHO ALL VALUES
}
You can do that with
$data = json_decode($json,true);
foreach($data["results"][0]["entities"][0]["urls"] as $value){
echo $value['expanded_url']."\n";
echo $value['url']."\n";
}
Since it's a multidimensional array, you can loop through the various levels to reach where you want.
foreach($data['results'] as $item) {
foreach($item['entities'] as $urls) {
foreach($urls['urls'] as $element) {
echo "expanded_url: {$element['expanded_url']} \n";
echo "url: {$element['url']} \n";
}
}
}
Note: The reason I've done the various foreach loops is due to the fact that there may be different results or different entities, so it's better to loop, than to do foreach($data["results"][0]["entities"][0]["urls"] as $value)
Example

need to read (echo) json by php

i need to get json code that changed remotely and display the data in php
when user load the page. (echo it)
i have this code:
(JSON output:)
{
"area 267":[
"city1",
"city2",
"city3",
"city4",
"city5",
"city6",
"city7",
"city8",
"city9",
"city10",
"city11",
"city12",
"city13"
],
"area 268":[
"city14",
"city15",
"city16"
],
"Coords":[
"31.856128;34.760947",
"31.8166376;34.729755",
"31.857223;34.727432",
"31.843444;34.751793",
"31.831039;34.722577",
"31.831504;34.756643",
"31.817725;34.7223",
"31.815936;34.752588",
"31.819054;34.739162",
"31.824913;34.747459",
";",
"31.813987;34.719103",
"31.833778;34.74009",
"31.815936;34.752589",
"31.819054;34.739163",
"31.824913;34.747458",
],
"ID":"1405796061262"
}
the coords lines is the sum of the all cities.
i need to echo the json like this:
(PHP output need to be like:)
ID: 1405796061262.
Areas: area267, area268.
Citys of Area267: city1, city2, ... city13. (echo all cities in the area)
Citys of Area268: city14, city15, city16. (echo all cities in the area)
i cant know the areas and the cities (that in the JSON file).
Thanks for helping :)
EDIT: WORKING CODE
<?php
$json_data = '{
"area 267":[
"city1",
"city2",
"city3",
"city4",
"city5",
"city6",
"city7",
"city8",
"city9",
"city10",
"city11",
"city12",
"city13"
],
"area 268":[
"city14",
"city15",
"city16"
],
"ID":"1405796061262"
}';
$data = json_decode($json_data);
//var_dump($data);
echo 'ID: ';
echo $data->ID;
echo '.<br>';
echo 'Areas: ';
$areas = array();
foreach ($data as $k => $v) {
if (strpos($k, 'ID') !== 0 && strpos($k, 'Coords') !== 0) {
$areas[] = $k;
}
}
echo implode(', ',$areas).'.<br /><br />';
foreach ($areas as $k => $v) {
echo "Cities of ".$v.': ';
$cities = array();
$cities = null;
foreach ($data->$v as $area) {
$cities[] = $area;
}
echo implode(', ',$cities).'.<br />';
}
?>
first you can use json_decode to convert the json output into php object then you can easily loop it and get the exact field value.
here is the documentation link:- http://php.net/manual/en/function.json-decode.php
Probably something like this should work
$data = json_decode($json_data);
echo 'ID '.$data['ID']."<br />";
echo 'Areas: ';
$areas = array();
foreach ($data as $k => $v) {
if (strpos($k, 'area ') === 0) {
$areas[] = $k;
}
}
echo implode(',',$areas).'.<br /><br />';
foreach ($areas as $area) {
echo "Cities of ".strtoupper($area).':';
$cities = array();
foreach ($data[$area] as $city) {
$cities[] = $city;
}
echo implode(','.$cities).'.<br />';
}

Categories