converting json branched array to php object - php

In below code, I want to display get_data using echo but not able to decode/display branched array. So, My question is how to convert branched array to PHP object.
Json Response :
{"status":1,"msg":"fetched Succesfully","user_data":{"d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba":{"name":"PRATYUSH","user_year":"2013","get_data":"d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba","is_active":1,"data_no":"ghjgjj2XXXXXXoioo7","user_bin":"77","is_exp":"N"}}}
PHP CODE :(after using curl)
$response = json_decode($o,true);
$status=$response["status"];
$msg=$response["msg"];
$user_data=$response["user_data"][0]["get_data"];
RESULT:
echo $status;//(working)
echo "<br>";
echo $msg;//(working)
echo "<br>";
echo $user_data;//(Not working)
echo User_data is not working.

So you want to get value of get_data. If d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba is not known, try this way.
$user_data_arr=$response["user_data"];
foreach($user_data_arr AS $user_data_obj)
{
echo $user_data_obj['get_data'];// here is your desired value
}
Using foreach loop, you do not have to find index and you can get values easily.
Full Code
$response = json_decode($o,true);
$status=$response["status"];
$msg=$response["msg"];
$user_data="";
$user_data_arr=$response["user_data"];
foreach($user_data_arr AS $user_data_obj)
{
$user_data = $user_data_obj['get_data'];// here is your desired value
}
echo $status;
echo "<br>";
echo $msg;
echo "<br>";
echo $user_data;//will work

Change
$user_data=$response["user_data"][0]["get_data"];
to this
$user_data=$response["user_data"]["d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba"]["get_data"];

Related

how to echo fixer.io json php

Hi I'm trying get a json from fixer.io and then for each rates echo it but cant get it to work.
the code are
<?php
function usd(){
echo 'HEJ test';
$fixer_access_key = my_access_key;
$url= 'https://data.fixer.io/api/latest?access_key=' . $fixer_access_key;
echo $url;
$json = file_get_contents($url);
$data = json_decode($json);
echo $url . "<br>";
echo 'printing json foreach <br>';
foreach($data as $obj){
echo '...';
$prefix = $obj;
echo $prefix;
echo '<br>';}
echo 'done printing json foreach';
}
usd(); ?>
and the result are:
https://data.fixer.io/api/latest?access_key=my_fixer_key
printing json foreach
done printing json foreach
instead of
$data = json_decode($json);
use
$data = json_decode($json, true);
This should allow foreacha to works - however you will only see first level of json object keys (not nested ones). The second parameter of json_decode change result from object to array.
You will also need to change foreach - to following: foreach($data as $key => $obj) and inside it echo $obj to echo $key;.
Here is simplified working example.
ALTERNATIVE SOLUTION
If working foreach is not your goal but rather pretty printed json, then instead use following code:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;

How to navigate the JSON hierarchy with PHP?

I am building a weather application that decodes a JSON file (found here: http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric)
The problem I am running into is navigating the JSON file in my PHP code to correctly select the tempature.
I need to do list->1->main->temp but this pulls up a number error in PHP. How do I correctly set the navigation?
echo "<form id='searchform' method='POST' action='https://projekt2-sofiamusick.c9users.io/wordpress/prognos/'>
Search: <input type='text' name='searchquery' placeholder='Search the forum' />
<input class='sendbutton_search' type='submit' name='search' value='>>' />
</form>";
if (isset($_POST['search'])){
$cityz = $_POST['searchquery'];
echo "<br>";
echo "<div id=apithing>";
$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=$cityz&appid=77f5e3fbc99649054660f82f871220f4&units=metric");
$jsonObject = json_decode($data, JSON_NUMERIC_CHECK);
json_encode( array( 'list' => (int)$jsonObject ) );
$list = $jsonObject->list;
$number = $jsonObject->'1';
$mains = $jsonObject->main;
echo $mains;
If you use JSON_NUMERIC_CHECK, your data present as array.
If you want get first element, just use $jsonObject['list'][0]
Without JSON_NUMERIC_CHECK, your data present as stdClass, and first element you can get with $jsonObject->list{0}
You can achieve it like this
$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric");
$jsonObject = json_decode($data);
if($jsonObject->cod == '200' && count($jsonObject->list) > 0){
foreach ($jsonObject->list as $jlk => $jlv) {
$dt = $jlv->dt;
$main = $jlv->main;
// your rest of logic
}
}
If you want you can see your data like this:
echo '<pre>';
var_dump($jsonObject);
echo '</pre>';
die;
Where you will see object, means you have to use "->" to access, and where you see array there use key of array to fetch that value.
Please feel free to ask, if any other doubt.

Getting data from a multidimentional array (Json)

How do I echo the 4 at the bottom?
$request_body = '{"id":8801236,"order_id":"1854071","accepted":true,"type":"Payment","text_on_statement":null,"branding_id":null,"variables":{},"currency":"USD","state":"pending","operations":
[{"id":1,"type":"authorize","amount":8996,"pending":false,"qp_status_code":"20000","qp_status_msg":"Approved","aq_status_code":"000","aq_status_msg":"Approved","data":
{},"callback_url":"http://www.mywebsite/callback.php","callback_success":true,"callback_response_code":"200","created_at":"2015-11-11T13:32:22+00:00"},
{"id":2,"type":"capture","amount":8863,"pending":true,"qp_status_code":null,"qp_status_msg":null,"aq_status_code":null,"aq_status_msg":null,"data":
{},"callback_url":null,"callback_success":null,"callback_response_code":null,"created_at":"2015-11-11T14:37:18+00:00"}],"metadata":
{"type":"card","brand":"visa","last4":"0008","exp_month":1,"exp_year":2019,"country":"US","is_3d_secure":false,"hash":"fdsfsdfsdf4ds65f4dsf65ds4"
,"number":null,"customer_ip":"8.1.1.21","customer_country":"US","fraud_suspected":false,"fraud_remarks":
[]},"link":null,"shipping_address":null,"invoice_address":null,"test_mode":true,"acquirer":"nets","facilitator":null,"created_at":"2015-11-11T13:32:13Z","balance":0}';
$request_array = json_decode($request_body, TRUE);
echo $request_array['qp_status_code']."<br />";
echo $request_array['qp_status_msg']."<br />";
echo $request_array['aq_status_code']."<br />";
echo $request_array['aq_status_msg']."<br />";
I have tried to do a print_r on the request_array, but honestly that only confuses me more. I simply can not see what array these variable lies within. I have tried to call them with both variables and operations but alas.
Your JSON feed has more than one "operations" which means you can call them like this (to get the first only):
echo $request_array['operations'][0]['qp_status_code']."<br />";
echo $request_array['operations'][0]['qp_status_msg']."<br />";
echo $request_array['operations'][0]['aq_status_code']."<br />";
echo $request_array['operations'][0]['aq_status_msg']."<br />";
Or if you need all of them you need to loop in it:
foreach ($request_array['operations'] as $operation) {
echo $operation['aq_status_msg']."<br />";
}

Foreach Loop grabbing JSON data

Could someone assist me in helping me display more than 1/2 results?
Here is my code:
$url = "http://otter.topsy.com/search.json?q=debt%20management&window=a&perpage=10";
$jsonfile = file_get_contents($url);
$obj = json_decode($jsonfile);
foreach($obj as $result) {
echo $obj->response->list[0]->trackback_permalink;
echo "<br />";
echo $obj->response->list[0]->trackback_author_nick;
echo "<br />";
echo $obj->response->list[0]->content;
echo "<br /><br />";
}
?>
*Note: I have taken out my API key.
Using that code it shows two of the same results.
Anyone got a solution?
You iterate over $obj which is the top-level object containing two elements (request and response). Since you probably want to iterate over the response list, this is what you need:
foreach($obj->response->list as $result) {
echo $result->trackback_permalink;
echo "<br />";
echo $result->trackback_author_nick;
echo "<br />";
echo $result->content;
echo "<br /><br />";
}
Ah, just saw it:
remove the $obj++ ! You increment twice during each loop run. Once by the foreach() loop iterating itself, and once by manually iterating.

How do I print all POST results when a form is submitted? [duplicate]

This question already has answers here:
Print out post values
(11 answers)
Closed 6 years ago.
I need to see all of the POST results that are submitted to the server for testing.
What would be an example of how I can create a new file to submit to that will echo out all of the fields which were submitted with that form?
It's dynamic, so some fields may have a name/ID of field1, field2, field3, etc.
All the values are stored in the $_POST collection
<?php print_r($_POST); ?>
or if you want something fancier that is easier to read use a foreach loop to loop through the $_POST collection and print the values.
<table>
<?php
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
?>
</table>
You could try var_dump:
var_dump($_POST)
Simply:
<?php
print_r($_POST);
//Or:
foreach ($_POST as $key => $value)
echo $key.'='.$value.'<br />';
?>
You may mean something like this:
<?php
$output = var_export($_POST, true);
error_log($output, 0, "/path/to/file.log");
?>
You could use something as simple as this
<?php
print_r($_POST);
?>
This would make it a bit more viewable:
<?php
echo str_replace(' ', ' ', nl2br(print_r($_POST, true)));
?>
You can definitely use var_dump, but you mentioned you are in front-end development. I am sure you would know this, but just as a reminder, use Firefox's Firebug or Chrome's / Internet Explorer's developers tool and check for the post. Post goes through hearders, and you should be able to check it from there too.
if (! function_exists('d'))
{
// Debugger
function d($var, $exit = 0)
{
// Only output on localhost
if ($_SERVER['HTTP_HOST'] != 'localhost')
{
return;
}
echo "\n[degug_output_BEGIN]<pre>\n";
echo var_export($var, 1);
echo "\n</pre>[degug_output_END]\n";
if ($exit)
exit;
}
}
// Call:
d($_POST);
Bonus: Check debug_backtrace() too add tracing to your debugging.

Categories