Convert JSON to PHP Array and Echo? - php

Here's my PHP code:
<?php
$json_url = "REDACTED";
$json = file_get_contents($json_url);
$stats = json_decode($json, true);
foreach ($stats as $row) {
echo $row['results']['result']['conversions'] . "<br />";
}
?>
Here's the JSON:
{
"metadata":{
"iserror":"false",
"responsetime":"0.07s"
},
"results":{
"first":1,
"last":99,
"total":99,
"result":[
{
"total_visitors":"3",
"visitors":"3",
"conversions":"0"
},
{
"total_visitors":"26",
"visitors":"26",
"conversions":"0"
},
{
"total_visitors":"13",
"visitors":"13",
"conversions":"0"
},
{
"total_visitors":"1",
"visitors":"1",
"conversions":"0"
},
{
"total_visitors":"1",
"visitors":"1",
"conversions":"0"
}
]
}
}
Essentially I'm just trying to echo the "conversions" from each section in the json file.
Never worked with a JSON file using PHP for, so I'm not really sure where I'm going wrong with this.

Need small correction in accessing array like below
foreach ($stats['results']['result'] as $row) {
echo $row['conversions'] . "<br />";
}
Because when you do json_decode, you will get array like below
Array
(
[metadata] => Array
(
[iserror] => false
[responsetime] => 0.07s
)
[results] => Array
(
[first] => 1
[last] => 99
[total] => 99
[result] => Array
(
[0] => Array
(
[total_visitors] => 3
[visitors] => 3
[conversions] => 0
)
[1] => Array
(
[total_visitors] => 26
[visitors] => 26
[conversions] => 0
)
[2] => Array
(
[total_visitors] => 13
[visitors] => 13
[conversions] => 0
)
[3] => Array
(
[total_visitors] => 1
[visitors] => 1
[conversions] => 0
)
[4] => Array
(
[total_visitors] => 1
[visitors] => 1
[conversions] => 0
)
)
)
)

It should be like following:
<?php
$json_url = "REDACTED";
$json = file_get_contents($json_url);
$stats = json_decode($json, true);
if ($stats && isset($stats['results']) && isset($stats['results']['result'])) {
foreach ($stats['results']['result'] as $row) {
echo $row['conversions'] . "<br />";
}
}
?>
So check if needed fields are set in JSON, and then loop for every result record to get the conversions.

$stats = json_decode($json, true);
foreach ($stats['results']['result'] as $row) {
echo $row['conversions'] . "<br />";
}

Related

Updating the value in existing JSON data by key in PHP

I have JSON data and want to update the value by key.
JSON:
{
"language":"en",
"education":[
{
"unit":"e1",
"language":"en"
}
],
"membership":[
{
"uei":"21",
"Uifed":"failed"
}
]
}
I want to change the value of uifed from "failed" to "success".
What have I done?
$json = '{"language":"en","education":[{"unit":"e1","language":"en"}],"membership":[{"uei":"21","Uifed":"failed"}]}';
$arrayData = json_decode($json, true);
$replacementData = array('Uifed' => 'success');
$newArrayData = array_replace_recursive($arrayData, $replacementData);
echo var_dump($newArrayData);
Result:
NULL
How can I do that?
That's not how array_replace_recursive works; the replacement arrays need to have the same structure as the one you are replacing into. For your sample data, this will work:
$json = '{"language":"en","education":[{"unit":"e1","language":"en"}],"membership":[{"uei":"21","Uifed":"failed"}]}';
$arrayData = json_decode($json, true);
$replacementData = array('membership' => array(array('Uifed' => 'success')));
$newArrayData = array_replace_recursive($arrayData, $replacementData);
print_r($newArrayData);
Output:
Array
(
[language] => en
[education] => Array
(
[0] => Array
(
[unit] => e1
[language] => en
)
)
[membership] => Array
(
[0] => Array
(
[uei] => 21
[Uifed] => success
)
)
)
array_walk_recursive can be used to do what you want:
$replacementData = array('Uifed' => 'success');
array_walk_recursive($arrayData, function (&$value, $key) use ($replacementData) {
$value = $replacementData[$key] ?? $value;
});
print_r($arrayData);
Output:
Array
(
[language] => en
[education] => Array
(
[0] => Array
(
[unit] => e1
[language] => en
)
)
[membership] => Array
(
[0] => Array
(
[uei] => 21
[Uifed] => success
)
)
)
Demo on 3v4l.org
Simple example with foreach and passing values by reference:
$json = '{"language":"en","education":[{"unit":"e1","language":"en"}],"membership":[{"uei":"21","Uifed":"failed"}]}';
$arrayData = json_decode($json, true);
foreach ($arrayData['membership'] as &$membership) {
if ('failed' === $membership['Uifed']) {
$membership['Uifed'] = 'success';
}
}
print_r($arrayData);
Fiddle.

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 transform array to this json pattern?

I have array something like this
Array
(
[0] => Array
(
[product_id] => 13
[unit] => 1
[price] => 20.0000
[total] => 20.0000
)
[1] => Array
(
[product_id] => 15
[unit] => 2
[price] => 30.0000
[total] => 10.0000
)
)
I was stuck to transform above array to the "ProductList" in the following pattern
array(
"UserID" => 2,
"ProductList" => [
{
"ProductID"=> 13,
"Price"=> 20.0000
},
{
"ProductID"=> 15,
"Price"=> 30.0000
}
]
)
I tried like this:
$products = [];
foreach($items as $item) {
if(!empty($item['product_id'])) {
$product = '{"ProductID"=>' . $item['product_id'] . '}';
$products[] = $product;
}
}
But not the expected result.
You're looking for json_encode(): http://php.net/manual/en/function.json-encode.php
Assign your array to a variable, for example $products, and then you can simply write json_encode($products) to achieve your desired result.
Try this,
$prodlist = array();
$x = 0;
foreach($arrs as $arr) {
//if ($arr['product_id'] == "" && $arr['price'] == "") continue;
$prodlist[$x]['Price'] = $arr['price'];
$prodlist[$x]['ProductID'] = $arr['product_id'];
$x += 1;
}
$arr2return['user_id'] = $user_id;
$arr2return['ProductList'] = $prodlist;
json_encode($arr2return);

I need help parsing .json array with php

Hi everyone I have a json named rushlist.json using this format:
{"rushlist":[{"Char":"Whipthemout","Pass":1,"Fail":1,"Status":"Free"}]}
I figured out how to display the whole array with this:
<?php
$Rushlist = json_decode(file_get_contents("rushlist.json"), true);
print_r($Rushlist);
?>
It displays :
Array ( [rushlist] => Array ( [0] => Array ( [Char] => Whipthemout [Pass] => 1 [Fail] => 1 [Status] => Free ) ) )
However I want to display just the element/value not this:
Array ( [rushlist] => Array ( [0] => Array ( [Char] => Whipthemout [Pass] => 1 [Fail] => 1 [Status] => Free ) ) )
Something like this
Rushlist
[Char] = Whipthemout
[Pass] = 1
[Fail] = 1
[Status] = Free
Any help would be great!
Thanks.
EDIT
<?php
$Rushlist = json_decode(file_get_contents("rushlist.json"), true);
print_r($Rushlist);
foreach($Rushlist as $arr_name=>$arr) {
print $arr_name . "\n";
foreach($arr as $key=>$value) {
print "[" . $key . "] = " . $value . "\n";
}
}
?>
Displays this:
Array ( [rushlist] => Array ( [0] => Array ( [Char] => Whipthemout [Pass] => 1 [Fail] => 1 [Status] => Free ) ) ) rushlist
Notice: Array to string conversion in F:\Share\test\Dropbox\test\test3.php on line 9
[0] = Array
foreach($Rushlist as $arr_name=>$arr) {
print $arr_name . "\n";
foreach($arr as $arr2 ) {
foreach($arr2 as $key=>$value) {
print "[" . $key . "] = " . $value . "\n";
}
}
}
That should do it.
UPDATED

Write JSON into a file with 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
)
)

Categories