Write JSON into a file with PHP - php

I have this JSON-File here
{
"id" : "bf75b277-169b-49da-8ab1-b78b8dfg1b43-e25c7f28b3",
"ts" : "1372751172664",
"connected" : {
"ssid" : "eduroam",
"bssid" : "00:0f:f9:eb:08:81",
"rssi" : "-62",
"speed" : "53"
},
"configured" : [
{
"ssid" : "eduroam",
"bssid" : "null",
"keyMgmnt" : ["2", "3"],
"grCiphers" : ["0","1","2","3"]
},
{
"ssid" : "foobar",
"bssid" : "null",
"keyMgmnt" : ["0"],
"grCiphers" : ["0","1","2","3"]
}
],
"location" : {
"prov" : "network",
"lat" : "52.3793203",
"lon" : "9.7231332",
"acc" : "22.777"
}
}
and I'm trying to get the key-value-pairs out into a file (and later into a mysql-database).
I am having trouble to go along the nested structure. Maybe I do not understand it correctly?
$LOGPATH = "/var/www/test/";
$out = fopen($LOGPATH."testlog.log", "a");
$result = file_get_contents('php://input');
$data = json_decode($result, true);
$value = $data;
$test = array();
This line beneath causes me headaches, how can I say get the key-value-pairs of "connected"?
Trying $test = $data['connected'] did not work, as the output simply is a "{" and nothing more...
$test = $data;
fwrite($out, "test \n");
fwrite($out, $test);
fwrite($out, "\n");
foreach ($test as $entry){
fwrite($out, $entry);
fwrite($out, "\n");
}
Any idea how to extract the key-value-pairs and/or help me understand the structure?

This should get you on the right track
foreach($data['connected'] as $key => $value){
echo 'Key: '.$key.' Value:'.$value.'<br>';
}

json_decode() will dump JSON into regular array. You can do print_r() or var_dump() on it, to see the structure of the array. So to get your connected leaf you do:
$connected = $data['connected'];
You can then iterate over it:
foreach( $connected as $key=>$val ) {
echo $key . ": " . $val;
}

Got it, thanks to you guys!
// Get a request from i.e. a webpage (this is a webservice)
$jsonArray = file_get_contents('php://input');
// put the JSON-Data into an array
$jsonData = json_decode($jsonArray, true);
// You can simply choose the entry-points. As they do not change for me, they are hardcoded in here, else you had to use something like a for-loop to extract them
$jsonConnect = $jsonData['connected'];
$jsonLocation = $jsonData['location'];
$jsonConfigured = $jsonData['configured'];
// walk through the JSON-Data and extract the values, although the array has more than 2 levels, you can select your entry-point and walk from there on, which makes this quite easy
for($i = 0; $i < count($jsonConfigured); $i++){
// keyMgmnt itself is an array and I want to concatenate all of its values and put it into a single field in my MySQL-DB, so implode() is used
$keyMgmnt = implode(",", $jsonConfigured[$i]['keyMgmnt']);
$grCiphers = implode(",", $jsonConfigured[$i]['grCiphers']);
$ssid = $jsonConfigured[$i]['ssid'];
$bssid = $jsonConfigured[$i]['bssid'];
// from here on I simply put the variables into my MySQL-DB
$sql_configured = "INSERT INTO configured (keyMgmnt, grCiphers, ssid, bssid) VALUES ('$keyMgmnt', '$grCiphers', '$ssid', '$bssid')";
mysql_query($sql_configured) or die ("Failure in configured");
}
$sql_connected = "INSERT INTO connected (rssi, speed, ssid, bssid) VALUES ('$jsonConnect[rssi]', '$jsonConnect[speed]', '$jsonConnect[ssid]', '$jsonConnect[bssid]')";
$enterConnected = mysql_query($sql_connected) or die("Failure in connection!");
$sql_location = "INSERT INTO location (lat, prov, lon, acc) VALUES ('$jsonLocation[lat]', '$jsonLocation[prov]', '$jsonLocation[lon]', '$jsonLocation[acc]')";
$enterLocation = mysql_query($sql_location) or die("Failure in location!");
Thanks again!
Case closed.
PS: The structure of the JSON-Data. You get it by using "print_r()" or "var_dump()".
(
[id] => bf75b277-169b-49da-8ab1-b78b80f51b43-e25c7f28b3
[ts] => 1372751172664
[connected] => Array
(
[ssid] => eduroam
[bssid] => 00:0f:f7:eb:08:81
[rssi] => -62
[speed] => 54
)
[configured] => Array
(
[0] => Array
(
[ssid] => eduroam
[bssid] => null
[keyMgmnt] => Array
(
[0] => 2
[1] => 3
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
[1] => Array
(
[ssid] => foobar
[bssid] => null
[keyMgmnt] => Array
(
[0] => 0
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
)
[location] => Array
(
[prov] => network
[lat] => 52.3793203
[lon] => 9.7231332
[acc] => 22.777
)
)
(
[id] => bf75b277-169b-49da-8ab1-b78b80f51b43-e25c7f28b3
[ts] => 1372751172664
[connected] => Array
(
[ssid] => eduroam
[bssid] => 00:0f:f7:eb:08:81
[rssi] => -62
[speed] => 54
)
[configured] => Array
(
[0] => Array
(
[ssid] => eduroam
[bssid] => null
[keyMgmnt] => Array
(
[0] => 2
[1] => 3
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
[1] => Array
(
[ssid] => foobar
[bssid] => null
[keyMgmnt] => Array
(
[0] => 0
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
)
[location] => Array
(
[prov] => network
[lat] => 52.3793203
[lon] => 9.7231332
[acc] => 22.777
)
)

Related

looping through multi dimension array

I am parsing A JSON file in PHP using PHP Decode
$json= file_get_contents ("resultate.json");
$json = json_decode($json, true);
and then I am trying to loop through the results and display them
foreach($json as $zh){
$name = $zh[0]["VORLAGEN"][0]["JA_PROZENT"];
$JA = $zh[0]["VORLAGEN"][0]["VORLAGE_NAME"];
$kreis = $zh[0]["NAME"];
$kreis1 = $zh[22]["NAME"];
echo $name;
echo $JA;
echo $kreis;
echo $kreis1;
...}
but I receive only one element e.g. position 0 or position 22. I would like to receive all the results and display them in a list. Below you can see the array
Array
(
[GEBIETE] => Array
(
[0] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 205
[STIMMBETEILIGUNG] => 28.11
[NEIN_STIMMEN_ABSOLUT] => 183
[VORLAGE_ID] => 2491
[JA_PROZENT] => 52.84
)
)
[NAME] => Aeugst a.A.
[WAHLKREIS] => 0
[BFS] => 1
)
[1] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 1000
[STIMMBETEILIGUNG] => 26.15
[NEIN_STIMMEN_ABSOLUT] => 851
[VORLAGE_ID] => 2491
[JA_PROZENT] => 54.02
)
)
[NAME] => Affoltern a.A.
[WAHLKREIS] => 0
[BFS] => 2
)
[2] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 661
[STIMMBETEILIGUNG] => 30.98
[NEIN_STIMMEN_ABSOLUT] => 454
[VORLAGE_ID] => 2491
[JA_PROZENT] => 59.28
)
)
[NAME] => Bonstetten
[WAHLKREIS] => 0
[BFS] => 3
)
can you please tell me how to print all the elements of this array?
There is GEBIETE layer in your json, so change foreach($json as $zh) to foreach($json["GEBIETE"] as $zh) will works.
You can nest multiple foreach:
$root = $json['GEBIETE'];
foreach ($root as $elem) {
foreach ($elem as $key => $value) {
// VORLAGEN is an array of its own so if you want to print the keys you should foreach this value as well
if(is_array($value)) {
foreach ($value[0] as $k => $v) {
echo $k."\t".$v;
}
}
else {
echo $value;
}
}
}

how to combine 2 array values into single one by common value

1.fetching the values from a same table with different date
<?php
$date= date("Y-m-d");;
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$result_yest=mysql_query("SELECT isp,sum(sent) AS `sent_yest` FROM red_global WHERE status_date='$prev_date' and sent > 0 group by 1",$link1);
$data_yest = array(); // create a variable to hold the information
while (($row_yest = mysql_fetch_array($result_yest, MYSQL_ASSOC)) !== false){
$data_yest[] = $row_yest; // add the row in to the results (data) array
}
print_r($data_yest);
$result_today=mysql_query("SELECT isp,sum(sent) AS `sent_today` FROM red_global WHERE status_date='$date' and sent > 0 group by 1",$link1);
$data_today = array(); // create a variable to hold the information
while (($row_today = mysql_fetch_array($result_today, MYSQL_ASSOC)) !== false){
$data_today[] = $row_today; // add the row in to the results (data) array
}
print_r($data_today);
exit;
?>
2.Array results in which one array contains yesterday's sent count and another one aray contains today's sent count both array having the common isp
Array (
[0] => Array ( [isp] => aol [sent_yest] => 46838 )
[1] => Array ( [isp] => gmail [sent_yest] => 33015 )
[2] => Array ( [isp] => juno [sent_yest] => 93544 )
[3] => Array ( [isp] => roadrunner [sent_yest] => 6181 )
[4] => Array ( [isp] => yahoo [sent_yest] => 71444 )
)
Array (
[0] => Array ( [isp] => aol [sent_today] => 14135 )
[1] => Array ( [isp] => att [sent_today] => 624 )
[2] => Array ( [isp] => gmail [sent_today] => 21263 )
[3] => Array ( [isp] => juno [sent_today] => 74934 )
[4] => Array ( [isp] => roadrunner [sent_today] => 939 )
[5] => Array ( [isp] => yahoo [sent_today] => 22059 )
)
Now i need a result like this isp name, yesterday's sent count, today's sent count
[isp, sent_yest, sent_today],
[aol, 46838, 14135],
[att, 0, 624],
[gmail, 33015, 21263],
Anyone help me to solve this.. Thanks in advance
Do it like below:-
$final_array = array();
if(count($arr1)>=count($arr2)){
foreach ($arr1 as $arr){
$key='';
foreach ($arr2 as $ar2){
if($arr['isp'] == $ar2['isp']){
$final_array[$arr['isp']] = array($arr['isp'],$arr['sent_yest'],$ar2['sent_today']);
$key ='';break;
}else{
$key = $arr['isp'];
}
}
if($key!==''){
$final_array[$key] = array($arr['isp'],$arr['sent_yest'],0);
$key ='';
}
}
}
if(count($arr2)>count($arr1)){
foreach ($arr2 as $ar2){
$key='';
foreach ($arr1 as $arr){
if($ar2['isp'] == $arr['isp']){
$final_array[$ar2['isp']] = array($ar2['isp'],$arr['sent_yest'],$ar2['sent_today']);
$key ='';break;
}else{
$key = $ar2['isp'];
}
}
if($key!==''){
$final_array[$key] = array($ar2['isp'],0,$ar2['sent_today']);
$key ='';
}
}
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/814625
I would avoid foreach if it's possible, since it leads to code that's much harder to understand. With array operation it can look like this:
// First we merge the two arrays
$merged = array_merge($data_yest, $data_today);
// Then format it
$final = array_reduce($merged, function($final, $item) {
// Initialize for each isp if it's not present
// This way we avoid overwriting previous data and have a default value 0
if (! isset($final[ $item['isp'] ])) {
$final[ $item['isp'] ] = [
'sent_yest' => 0,
'sent_today' => 0,
];
}
// And if one of the days is present, we add it
if (isset($item['sent_yest'])) {
$final[ $item['isp'] ][ 'sent_yest' ] = $item['sent_yest'];
}
if (isset($item['sent_today'])) {
$final[ $item['isp'] ][ 'sent_today' ] = $item['sent_today'];
}
// Then return the modified array
return $final;
}, []);
print_r($final);
exit;
Result looks like this:
Array
(
[aol] => Array
(
[sent_yest] => 46838
[sent_today] => 14135
)
[gmail] => Array
(
[sent_yest] => 33015
[sent_today] => 21263
)
[juno] => Array
(
[sent_yest] => 93544
[sent_today] => 74934
)
[roadrunner] => Array
(
[sent_yest] => 6181
[sent_today] => 939
)
[yahoo] => Array
(
[sent_yest] => 71444
[sent_today] => 22059
)
[att] => Array
(
[sent_yest] => 0
[sent_today] => 624
)
)

Array foreach modification

I have an array $testing like this :
Array (
[CUST_TYPE] =>
Array (
[0] => Family
[1] => Regular
[2] => Corporate
[3] => Premium )
[TOTAL_BALANCE] =>
Array (
[0] => 420946131.01
[1] => 41272033223.93
[2] => 38873647942.4
[3] => 10465337565.61 )
)
I need to convert (print) this array into something like this :
{
cust_type : Family,
balance : 420946131.01
},
{
cust_type : Regular ,
balance : 41272033223.93
},
and so on..
Here is simple foreach that I used, but it can only print cust_type or balance
$cols = array_keys($testing);
foreach ($testing[$cols[1]] as $i => $j) {
echo '{cust_type : ' . $j .
', balance : ' . $<What should I print??> . '},';
}
Kindly please to help.
Thank you.
Consider this snippet,
for($i=0; $i<count($your_array['CUST_TYPE']); $i++)
{
$required[] = [ 'cust_type' => $your_array['CUST_TYPE'][$i],
'balance' => $your_array['TOTAL_BALANCE'][$i] ];
}
$required = json_encode($required);
will output,
[{"cust_type":"Family","balance":420946131.01},{"cust_type":"Regular","balance":41272033223.93},{"cust_type":"Corporate","balance":38873647942.4},{"cust_type":"Premium","balance":10465337565.61}]
For other format, You can use array_combine() creates an array with first argument as keys and second as values,
The format you are specifying is json So, json_encode() will do that for you,
$required = array_combine($your_array['CUST_TYPE'], $your_array['TOTAL_BALANCE']);
$required = json_encode($required);
Now, $required is string with your desired value. Which is,
{"Family":420946131.01,"Regular":41272033223.93,"Corporate":38873647942.4,"Premium":10465337565.61}
Note: Make sure you have same number of members in both $your_array['CUST_TYPE'] and $your_array['TOTAL_BALANCE'] arrays inside your input array. Otherwise you will see a warning.
Using array_map (PHP 4 >= 4.0.6, PHP 5)
$json = json_encode(array_map(function($a,$b){ return array("cust_type"=>$a,"balance"=>$b);},$array["CUST_TYPE"],$array["TOTAL_BALANCE"]));
Test
[akshay#localhost tmp]$ cat test.php
<?php
$array = array(
"CUST_TYPE" => array(
'Family',
'Regular',
'Corporate',
'Premium'
),
"TOTAL_BALANCE" => array(
420946131.01,
41272033223.93,
38873647942.4 ,
10465337565.61
)
);
// PHP 4,5
$json = json_encode(array_map(function($a,$b){ return array("cust_type"=>$a,"balance"=>$b);},$array["CUST_TYPE"],$array["TOTAL_BALANCE"]),JSON_PRETTY_PRINT);
// Input
print_r($array);
// Output
print $json."\n";
?>
Output
[akshay#localhost tmp]$ php test.php
Array
(
[CUST_TYPE] => Array
(
[0] => Family
[1] => Regular
[2] => Corporate
[3] => Premium
)
[TOTAL_BALANCE] => Array
(
[0] => 420946131.01
[1] => 41272033223.93
[2] => 38873647942.4
[3] => 10465337565.61
)
)
[
{
"cust_type": "Family",
"balance": 420946131.01
},
{
"cust_type": "Regular",
"balance": 41272033223.93
},
{
"cust_type": "Corporate",
"balance": 38873647942.4
},
{
"cust_type": "Premium",
"balance": 10465337565.61
}
]

Adding Elements To An StdClass Array - PHP / Codeigniter

I have an array that is an stdClass. The output of that array is as follows :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
)
What I would like to do is add two variables to this stdClass. They are "total_bookings" and "total_venues";
I currently am looping through the results and then getting a count to create the total. I would like to add those two vars to the end of that stdClass array.
My PHP is as follows :
$vendors = $this->po_model->get_all_vendors();
$this->template->set('total_vendors', count($vendors));
$count = 0;
foreach($vendors as $vendor)
{
$count++;
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$count]['total_venues'] = $total_venues;
$vendors[$count]['total_bookings'] = $total_bookings;
}
However, When I var_dump that my Array looks like this :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
[1] => Array
(
[total_venues] => 6
[total_bookings] => 14
)
)
So my question is, How do I add total_venues and total_bookings to that stdClass()?
Thanks
$myArray[$indexOfObject]->total_venues = 6;
$myArray[$indexOfObject]->total_bookings= 14;
Your example:
foreach($vendors as $key => $vendor)
{
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$key]->total_venues = $total_venues;
$vendors[$key]->total_bookings = $total_bookings;
}
its an object, you should use object notations, not array notations. also change your move your count++ below these two instructions
$vendors[$count]->total_venues = $total_venues;
$vendors[$count]->total_bookings = $total_bookings;
$count++;

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories