Error while trying to read posted json data in php - php

I have the following problem. When i am trying to read some json data that are posted from an html page, i'm facing with the following error "Trying to get property of non-object on line".
Jquery script to create the json
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
Jquery for posting to php
$.post("page.php",{jsonData: JSON.stringify(json),
customer: $("#cusID").val()},function(data){});
PHP file
$json = json_decode($_POST['jsonData']);
foreach($json as $value){
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
Thanks in advance.

Thereafter:
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
You have:
Object[data][0] = array('serialNumber' => ...);
Need:
$json = json_decode($_POST['jsonData'][0]);
or
$json = json_decode($_POST['jsonData']);
foreach($json as $row){
foreach($row as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
}

json_decode without second parameter returns result as php object. You have to pass true as second parameter. Also your data are in $json['data'], not $json:
$json = json_decode($_POST['jsonData'], true);
foreach($json['data'] as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}

Related

Using foreach Loop In PHP To Parse Json

I'm using iTunes RSS generator to get HOT tracks, now I'm using following way to parse JSON:
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'][0]['collectionName'];
echo $cltn;
?>
Now, as we know that It'll return only 1 collectionName.
JSON request is returning 10 results. How can I get them all using foreach loop? I've used several ways but no success.
Since you didn't give the output of the array I assume the [0] index is what needs to be iterated.
You need to foreach the $obj['feed']['results'] by doing:
Foreach($obj['feed']['results'] as $cltn){
Echo $cltn['collectionName'];
}
Foreach over the results:
foreach ($obj['feed']['results'] as $result) {
echo $result['collectionName'] . '<br>' . PHP_EOL;
}
Based on the code you provided you can iterate the results to get all possible information from the artist/track list, for example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
function test_print($item, $key)
{
echo "<strong>".$key."</strong>: ".$item."<br>";
}
foreach($cltn as $key => $c) {
echo "Result No ".($key+1)."<br>";
array_walk_recursive($c, 'test_print');
}
in case you only want to show artistName and collectionName you can slightly modify the above example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
foreach($cltn as $c) {
echo $c['artistName'].": ".$c['collectionName']."<br>";
}
You can try all the above in PHP Fiddle
Try like this way with foreach() to iterate your array in key=>value manner as you've decoded the json as an array not an object in php.
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$array = json_decode($jsondata,true);
# printing resulted array just for debugging purpose
print '<pre>';
print_r($array);
print '</pre>';
foreach($array['feed']['results'] as $key=>$value){
echo $value['collectionName'].'<br/>';
}
?>

i cant get json array value using loop for (PHP)

i have 1 json but i cant get a value using for loop
$string = [{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]
$json = json_decode($string,true);
for($i = 0;$i<count($json);$i++){
for($j = 0;$j<count($json->lot);$i++){
if($json->lot==0){
echo $j;
}
}
}
i got this error : Trying to get property of non-object
edit your code :
$json = [{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]
$json = json_decode($json);
for($i = 0;$i<count($json);$i++){
for($j = 0;$j<count($json->lot);$i++){
if($json->lot==0){
echo $j;
}
}
changes json to decode in array using php json_decode(). json_decode
You need to use json_decode on your json. Also, keep in mind that json have to be stored as string in PHP.
<?php
$json = ['{"lt":"1","lot":["1","1","1","1","1"]}','{"lt":"2","lot":["0","0","0","0","0"]}','{"lt":"3","lot":["0","0","0","0","0","0"]}'];
foreach($json as $data) {
$current = json_decode($data);
foreach($current->lot as $lot)
echo $lot;
}
Used json_decode() function for decode json :
<?php
$json = '[{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]';
$json = json_decode($json);
foreach($json as $val){
foreach($val->lot as $lot) {
if($lot==0){
echo $lot;
}
}
}
?>

Loop through JSON and store values to PHP arrays

I have a JSON with the Following structure.
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
I need the Itemname to be made into a PHP array, Unitprice into another one, Qty to another one and price to another one. How do I do that?
$getArray = get_object_vars(json_decode($json));
print_r($getArray);
echo $getArray[1]->Itemname;
echo $getArray[1]->unitprice;
you require get_object_vars as well for achieving your requirement.
<?php
$json =<<<JSONLIVES
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
JSONLIVES;
$items = json_decode($json, TRUE);
$item_names = array();
foreach($items as $key => $item) {
$item_names[] = $item['Itemname'];
}
Or Php >= 5.5
print_r(array_column($items, 'Itemname'));
You need a function called json_decode() to convert your json data into PHP array
$json = {
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
};
var_dump(json_decode($json));
You need to decode your Json by PHP's json_decode()
$decodeJson will return object then you can read Itemname and other values by using $val->Itemname in foreach loop
$json = '{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}';
$decodeJson = json_decode($json);
foreach($decodeJson as $key=>$val) {
print_r($val);
}
Live Json decode
Try that:
$json = json_decode($json);
foreach($json as $obj){
echo $obj->name;
.....
}
After some research, I found out that the most efficientt way that solves my problem here would be to do like the following.
$cash=json_decode($new_json, true);
echo $arr3[1]['Itemname'];
echo $arr3[1]['unitprice'];
:
:
and so on.
This can be put into loops easily, fetched into HTML text-fields (as I want here in this scenario) and so on.

JSON manipulation in PHP?

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1

How to loop json and parse the value

This is my php code [EDITED]:
$redis_data = file_get_contents("http://example.org/data/data.txt");
That code returns the following json data:
{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302}
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302}
This is my code to looping parse the value:
$redis_data = file_get_contents("http://example.org/data/data.txt");
$redis_data = json_decode($redis_data, true);
foreach ($redis_data as $data) {
echo $data['Phone'];
echo "<br>";
}
But I got this errors:
Invalid argument supplied for foreach()
What am I doing wrong?
The data you trying to get is not well formatted json
[{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"}]
This is the json syntax.
and you are getting data in following format.
{"ANumber":"08122378673","BNumber":"500046","StartTime":"08122014102113","EndTime":"08122014104126","TrunkA":"S1JK2SBD1S","TrunkB":"N7JK2GSM1B","Customer":"PT.BNI","time":1407921302}
{"ANumber":"081351607600","BNumber":"14000","StartTime":"08122014102406","EndTime":"08122014103738","TrunkA":"S1JK2SSB1S","TrunkB":"EPJK2MNR0","Customer":"Bank Mandiri (CC_IB_Jasnita)","time":1407921302}
You may need to reformat your data string
You're trying to loop JSON - not PHP. You need to run json_decode (docs) on the your $redis_data variable before attempting to loop it.
$redis_data = json_decode($redis_data, true);
You need to decode the json before you can loop through it.
$redis_data = json_decode(file_get_contents("http://example.com/tes_files/data.txt"), true);
foreach ($redis_data as $data) {
echo $data['phone'];
}
Here is solution
$redis_data = explode( chr(10), file_get_contents("http://example.com/tes_redis/data.txt"));
foreach ($redis_data as $data) {
var_dump(json_decode($data));
$data = json_decode($data);
echo $data->Phone;
echo $data->StartTime;
echo $data->Customer;
//echo $data->ANumber;
//echo $data->BNumber;
}
you need to export data first.
first you have to convert json to array using json_decode function it will give array and after that you can loop
`
$jsonString =
'[{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302},
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302},
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302} ]';
$array=json_decode($jsonString);
foreach ($arrayOfEmails as $data) {
echo $data->Phone."<br>";
}
`

Categories