Hello i am new with Json in php. I have a web service that gives me data in json format.
I take this data making decode put when i try to use this data i cant
Here is my code:
$url = "http://www.webinsurer.gr/....;
$json = json_decode(#file_get_contents($url), true);
and if i make debug i see the data i take :
[file] => C:\xampp\htdocs\development.insurancemarket.gr\mvc\protected\models\Ratingsmail.php
[line] => 18
[data] => Array
(
[0] => Array
(
[POL_EXPIREDATE] => 2014-05-19 12:00:00
[INCO_IWCODE] => 41
[INCO_DESC] => MAPFRE ASISTENCIA
[PACK_IWCODE] => 0
[PACK_DESC] =>
[OFFERCODE] =>
[PAYMENTCODE] =>
)
[1] => Array
(.....
But i dont now how to use that data. when i try this :
$b= $json->{1}->{'INCO_IWCODE'};
Debug::debuger($b);
the result is nothing
what is wrong? sorry for long post.
When setting the second argument on json_decode to true, you are actively asking for the data to be returned in an associative array and not objects. Thats why your code didn't work.
Demo
You are converting json to associative array. You need to use;
$b = $json["data"][1]["INCO_IWCODE"];
$a = $json[0]->INCO_IWCODE;
That worked for my guys. thanks you all!!!
Related
$receipt array give the below output. How to get orderId ?
pr($data); die;
to get orderId, $data['receipt']['orderId']; But its gives me error..
App\Model\Entity\PaymentDetail Object
(
[id] => 4
[user_id] => 4
[company_id] => 5
[receipt] => {"orderId":"GPA.3312-5688-8401-53436","packageName":"com.kenbar.mynus2","productId":"com.mynus2.subscription99","purchaseTime":1534914306517,"purchaseState":0,"purchaseToken":"gefffblagdakjleamfngklli.AO-J1Ow9Q5PncOoRk-oshlRBQ8kVqt3A4uIZuQi6InX7sr4bx2lNzjS-VjOXyMIwkl2G-afrI0fzoVLEADNZP2RWekoxwe4ko1M884JALYhaZsxo44U9DshbKJxbDNQHcCx9_z0yQpxc","autoRenewing":true}
)
$orderJson = json_decode(data['receipt'],true);
print_r($orderJson['orderId']);
As data['receipt'] contains a JSON string you need to parse it externally before consuming it as an object.
$orderId=json_decode($your_array->receipt);
echo $orderId->orderId;
You have a json as a string in your stdClass object field so you need to decode it first before you access it.
The above code will work for you.
You can use
$order_id = json_decode($data->reciept, true)["orderId"];
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.
This is the code so far:
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
End result: NULL NULL NULL
What am I doing wrong?
Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);
Try access your array that way.
The output is :
0000
6998000
Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.
Have you read the documentation of json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.
The elements in a PHP array can be accessed using the square bracket syntax.
A simple call to print_r($results) tells its structure:
Array
(
[status] => 0000
[data] => Array
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
Now, accessing its items is a piece of cake:
echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000
Remove true from json_decode so you will have object result like Demo
$results = json_decode($api_results);
var_dump($results->status);
var_dump($results->data->opening_price);
When you use json_decode with true the returned objects will be converted into associative arrays.
Use this code like i think work it fine..
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results);
print_r($results);
var_dump($results->status);
$var = $results->data;
var_dump($var->opening_price);
?>
stdClass Object
(
[status] => 0000
[data] => stdClass Object
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
string(4) "0000"
string(7) "6998000"
Remove true from json_decode and try something like this:
var_dump($results->status);
var_dump($results->data->opening_price);
If you see {} it is refering to objects and [] indicates that it is an array. You're trying to show everything as if they were arrays
You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).
You may access the data like this:
var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);
P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.
I need one help. I am unable to convert string to json array using PHP. I am explaining my code below.
$education=$_POST['education'];
the above line give this output [{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]. But its coming as a string .I tried to convert into array like below but it gived output as null
$edu=json_decode($education,true);
print_r($edu);
It gives the empty output. Here I need to convert it to array and populate all data. Please help me.
Hi You need to make your json string like below:
$arr = '[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]';
$a = json_decode($arr);
echo "<pre>";
print_r($a);
die;
it will show your output like below:
Array
(
[0] => stdClass Object
(
[name] => aaa
[id] => 12
)
[1] => stdClass Object
(
[name] => bbb
[id] => 20
)
)
In php, you can use this function to check valid json:
function _isJsonString($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
You can also check online for valid json: http://json.parser.online.fr/
Hope this will help.
I am using jQuery to convert form data to serialized form using:
var data = $('#frm').serialize();
In php I get this:
fiscalyear_id=4&category=Category+A&isgraph=on&Title=a&Value=a&Title=b&Value=b&category=Category+B&Title=c&Value=c&Title=d&Value=d&category=Category+C&Title=e&Value=e&Title=f&Value=f&data;=&csrf_check=9c288285b379701b27c3836091c00b04
And when I do:
parse_str($_POST['data'], $data);
pretty_print($data);
I get:
Array
(
[fiscalyear_id] => 4
[category] => Category C
[isgraph] => on
[Title] => f
[Value] => f
[data;] =>
[csrf_check] => 9c288285b379701b27c3836091c00b04
)
As can be seen, not all paramters are coming in array above. Does anyone have an idea what I am doing wrong ? Thanks for the help
parse_str parses the string in variable and you are getting it into array.
but duplicate array keys are not possible,
hence you are not getting all the values because they have the same key!
Array
(
[0] => Array
(
[price_id] => 1
[website_id] => 0
[all_groups] => 1
[cust_group] => 32000
[price_qty] => 2
[price] => 90.0000
)
[1] => Array
(
[price_id] => 2
[website_id] => 0
[all_groups] => 1
[cust_group] => 32000
[price_qty] => 5
[price] => 80.0000
)
.......
)
the array element maybe one or two or more, if i want to pass [price_qty] and [price] value to the jquery code. how should i do? could someone make me an example. thank you
you should consider using JSON strings in order to use key based arrays in JavaScript.
http://php.net/json
json_encode your php arrays to json
Use json_encode to convert your php array to json :)
A possible solution is to convert php array structures into JSON before passing the data to the client.
Have a look at php json.
And also have a look at this post.
Try with Json:
json_encode($array);
This will encode the array into a json object, that is friendly with javascript (and Jquery).
If you are passing it through an ajax request just echo it in the php and return that as response.
If it's in the same script you could do:
$object = json_encode($array);
echo "var myObject = $object;";
And for accessing the information in javascript/jquery you would do:
alert(myObject[0].price_id);
you use myObject[0] to access positions as in php arrays, and myObject[0].name to access what would be associative array key in an array.
For more information visit json documentation page
Well while you ask to move from [php]array to [javascript]array, this is how to. You should ue json_encode how the previous answer said, but in you javascript you can use the following code to convert a json into an array:
function json2Array = function(json){
var a = [];
for(var o in json){
a.push(json[o]);
}
return a;
}
var myArray = json2Array(youPhpJsonEncode);
and you will have your array in javascript