Parse JSON File with PHP - php

I had a problem when parse my json data with php in select html element
This my JSON DATA
This my PHP CODE
Error message :
Notice: Trying to get property of non-object in C:\xampp\htdocs\test\index.php on line 6
This line 6 :
$provider = $jfo->product->provider;
I try to parse "provider" to select html element after someone choose "Jenis Produk".

product is not an object, it is an array:
$jfo->product['provider'];

product is an array, containing multiple products.
$jfo->product[0]->provider;
You'll need to loop through the products.
for ($i = 0; $i < sizeof($jfo->product); $i++) {
$provider = $jfo->product[$i]->provider;
}

It appears that product is not an object.
Have you tried dumping $jfo->product?
My guess is that it is an array.

Related

PHP edit JSON MySQL table

I need some help, I can't get it done...
I have a database, called "db"
Inside I have a table named "objects"
In this table there is a column named "details" which contain a JSON (see image)
In a PHP script I want to edit the "cost" parameters based on the value of the "type" and the other parameter named "source" to keep his value.
For example, if type is small -> cost = 1
type = big -> cost = 2.
Any ideas?
I have tried several but I received warning:
Warning: Attempt to assign property of non-object
Notice: Array to string conversion
To edit the JSON data in the details column you would have to first decode the JSON like so:
$query //This be equal to your query data from the db containing the table data
$json = $query["details"];
$d_coded_json = json_decode($json);
if($d_coded_json->type == "small"){
$d_coded_json->cost = 1;
}else if ($d_coded_json->type == "big"){
$d_coded_json->cost = 2;
}
// you can convert to back to json by running the code below
$new_json = json_encode($d_coded_json);
// save back to db

Json file parsing in PHP

I'm trying to parse the following Json file:
{
"Itineraries" : [{
"date1" : "20/Jan/2016",
"date2" : "20/Jan/1996",
"Options" : [
{
"Num_ID" : [398],
"Quotedwhen" : today,
"Price" : 330.00
}
]
}
]
}
I'm using the following PHP code:
$json2 = file_get_contents("data.json");
var_dump(json_decode($json2));
$parsed_json2 = json_decode($json2);
$price = $parsed_json2->{'Itineraries'}->{'Options'}->{'Price'};
And I get the following error (Line 35 is the last line of the PHP code above):
Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/jsonread.php on line 35
Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/jsonread.php on line 35
Do you have any idea of how to solve this problem?
You have to put the string
today
In double qoutes
"today"
Because its a string :)
the reason you are getting that message is because the json_decode() is failing to return an object because your JSON is invalid. You need to put double quotes around today. You are also accessing the data incorrectly.
Here's the correct code to get the price:
echo($parsed_json2->Itineraries[0]->Options[0]->Price);
You have created a lot of arrays here which only have one item in them, are you intending to have multiple itinerary, multiple options objects, and multiple Num_IDs per options object? If not you can get rid of a lot of those square brackets.

How to get all the colums using one-one and one-many and other in NotORM and PHP?

Here is what I have done:
$meetups = $db->meetups()->where("ID > ?", "15");
foreach ($meetups as $meetup) {
$location[] = $meetup->locations();
}
echo json_encode($locations[0]->getIterator());
As shown in the above snippet I'm trying to output the JSON string of the meetup location and using fiddler I get this error:
Fatal error: Call to undefined method NotORM_MultiResult::getIterator() in C:\xampp\htdocs\latest\Server\Routes\Meetups.php on line 204
What am I doing wrong? This works well:
$meetups = $db->meetups()->where("ID > ?", "15");
foreach ($meetups as $meetup) {
$location[] = $meetup->locations['Title'];
}
echo json_encode($locations);
But I don't want to get just Title of the location. I want all the columns.
My table structure is:
meetups table
ID, Title, locations_ID, ...
locations table
ID, Title, LocationLat, LocationLng, ...
The error message implies that the $locations[0] object doesn't offer a getIterator() method.
That object has a method called jsonSerialize, a property called jsonAsArray, and a $rows property.
From NotORM FAQ:
How to create a plain array from NotORM result?
You can use iterator_to_array:
// inner call converts the rows, outer call converts the fields
array_map('iterator_to_array', iterator_to_array($db->application()));
Your code may be as well reduced to this one-liner:
echo json_encode(array_map('iterator_to_array', iterator_to_array($db->meetups('ID > ?', 15))));

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

Get list of top friends for facebook app

I am Creating A facebook that Retrieves 10 Random friends.But I need some code to Retrieve Top friends using comment and like ativity.I used Following code but i get below error
Invalid argument supplied for foreach()
below is the code i tried so far.
$statuses = $facebook->api('/me/statuses');
foreach($statuses['data'] as $status){
// processing likes array for calculating fanbase.
foreach($status['likes']['data'] as $likesData){
$frid = $likesData['id'];
$frname = $likesData['name'];
$friendArray[$frid] = $frname;
}
foreach($status['comments']['data'] as $comArray){
// processing comments array for calculating fanbase
$frid = $comArray['from']['id'];
$frname = $comArray['from']['name'];
}
That error message generally happens when your array variable is not set. If you could add line numbers to your code and give the full error message (including line number) it might help.
Can you show a print_r of $statuses['data']?
I've been trying to get this to work myself. Found the solution. $facebook->api() is going to return a json array. This is not a valid element for a foreach() statement. You need to use json_decode($statuses) in order to loop through the array in the foreach() statement.
Foreach through JSONArray in PHP

Categories