Json extra fields - php

I created this working code which is storing data from an api to a json file
based on yesterday's date.
$filedate = date('Y-m-d',strtotime("-1 days"));
$yesterday = date('Y-m-d 00:00',strtotime("-1 days"));
$today = date('Y-m-d 23:59',strtotime("-1 days"));
try{
$soccer=new XMLSoccer("API KEY");
$soccer->setServiceUrl("http://www.xmlsoccer.com/FootballData.asmx");
/* $result=$soccer->GetLiveScore();*/
$result=$soccer->GetFixturesByDateInterval(array( "startDateString"=> "$yesterday" ,"endDateString"=> "$today"));
var_dump($result);
$fp = fopen( "/var/www/public_html/domain/$filedate.json","w+");
fwrite($fp,json_encode($result));
fclose($fp);
}
catch(XMLSoccerException $e){
echo "XMLSoccerException: ".$e->getMessage();
}
The code above stores this json data in the file :
{
Match: [
{
Id: "346528",
Date: "2015-07-15T12:00:00+00:00",
League: "Chinese Super League",
Round: "19",
HomeTeam: "Guangzhou Evergrande",
HomeTeam_Id: "1108",
HomeGoals: "0",
AwayTeam: "Henan Jianye",
AwayTeam_Id: "1100",
AwayGoals: "0",
Time: "Not started",
Location: "Tianhe Stadium",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
},
{
Id: "346527",
Date: "2015-07-15T11:45:00+00:00",
League: "Chinese Super League",
Round: "19",
HomeTeam: "Shanghai Greenland Shenhua",
HomeTeam_Id: "1107",
HomeGoals: "0",
AwayTeam: "Beijing Guoan",
AwayTeam_Id: "1098",
AwayGoals: "0",
Time: "Not started",
Location: "Hongkou Football Stadium",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
},
}
Right now I need to add some extra fields for each match, for example if HomeTeam = Real Madrid , add extra field HomeTeamShort = RMD etc. This should be done dynamically because I have to create IF's for each away and home team.
Somebody can help how can i do this ?

First you have to decode your json
$array = json_decode($result);
Get the Match array
$arr = $array->Match;
Now loop through all the objects (i.e.) and do whatever necessary
foreach($arr as $item) { //foreach element in $arr
//do whatever you want to do with that object
if($item->HomeTeam == "Real Madrid") {
$item->HomeTeamShort = "RMD";
}
}
print_r($arr); //Now $arr is the required result you wanted to have
//you can also convert your array back json
$arr2 = json_encode($arr);
Please let me know if you wanted something else and I will change my code to address your need.
Thank you.
* ADDITIONAL HELP WITH EXAMPLE *
Check if you have put the variables and arrays of object properly before running the loop. Since I can't see what you have really done in your code and what your line numbers are, I am pasting a full dummy code along with outputs, please compare it with your own code and you should be able to get the proper output.
<?php
//let's take an example json data
$result = '{"Match":
[
{"name":"Tom", "age":22},
{"name":"Jerry", "age":20},
{"name":"Hank", "age":25}
]
}';
$array = json_decode($result);
$arr = $array->Match;
Let's print the array once before processing
print_r($arr); //Array ( [0] => stdClass Object ( [name] => Tom [age] => 22 ) [1] => stdClass Object ( [name] => Jerry [age] => 20 ) [2] => stdClass Object ( [name] => Hank [age] => 25 ) )
Now do the loop thing and add whatever property you need to whichever object you want
foreach($arr as $item) { //foreach element in $arr
//do whatever you want to do with that object
if($item->name == "Jerry") {
$item->color = "Brown";
}
}
Now if you print the array again you will see Color Brown has been added to Jerry
print_r($arr); //Array ( [0] => stdClass Object ( [name] => Tom [age] => 22 ) [1] => stdClass Object ( [name] => Jerry [age] => 20 [color] => Brown ) [2] => stdClass Object ( [name] => Hank [age] => 25 ) )
Convert your array back json if you want
$arr2 = json_encode($arr);
Now, check the json, you will also see the Color Brown there against Jerry
var_dump($arr2); //string(92) "[{"name":"Tom","age":22},{"name":"Jerry","age":20,"color":"Brown"},{"name":"Hank","age":25}]"
?>
This is step by step analysis and explanation of this code. As you can see I am not getting any undefined object error. So, try copy pasting my above code and if you can replicate the same error, then it will be easy for me to understand what is causing your bug.
I have also made a PHPFiddle Link here, you can check the code and run it also there.
Thanks again.

Thank you for your help, don't solve my problem but make me progress(i'm getting close )
Maybe it's my mistake, because i don't provide some important things
So.. i test your code on phpfiddle and it works, and works mostly because you have the json directly on the code, in my project i need to open the file.json from the server, and with your code even adapting a few things , i get some errors, so ... i change your code a little bit :
<?php
$json_url = "http://getinstagoal.com/2015-07-20.json";
$json = file_get_contents($json_url);
$links = json_decode($json, TRUE);
foreach($links["Match"] as $key=>$val) {
if($val['HomeTeam'] == "Palmeiras") {
$val['HomeTeamshor'] = "RMD";
}
}
//you can also convert your array back json
$arr2 = json_encode($links);
//print the json, you will also see the Color Brown there against Jerry
var_dump($arr2); //string(92) "[{"name":"Tom","age":22},{"name":"Jerry","age":20,"color":"Brown"},{"name":"Hank","age":25}]"
?>
with that code i was able to get the right data, i try with some echo and etc.
however the file update didn't work even running php as root on the server, i check and "if" works (i test it with "echo") i try with file_put_content didn't work, the only way that i successfully do add something to the json file was creating and array of the content but that will rewrite the entire file. Any idea about that ?
Other thing, i will need to do "if" 8 items per match something like
if($val['HomeTeam'] == "Real Madrid") {
$val['HomeTeamshort'] = "RMD";
}
if($val['AwayTeam'] == "Barcelona") {
$val['AwayTeamshort'] = "FCB";
}
for more than 1300 (it should compare in the file, usually it's 20 games per day, not that much)
What is the most efficient way that i have to do this "ifs" to each match ?
Thank you #Suman

Related

How to locate an array in a php object with no key

I have a database of zip codes from The Zip Code Database Project that came as a .csv file. I converted it to json and it has no key for each array, they look like this:
[
{
"zipcode": 35004,
"state abbreviation": "AL",
"latitude": 33.606379,
"longitude": -86.50249,
"city": "Moody",
"state": "Alabama"
}
]
I have figured out how to search all of the arrays and locate a matching zip code but I can't figure out how to make that search return data about the array that it found it in.
I can search like this:
$filename = './assets/data/zips.json';
$data = file_get_contents($filename);
$zipCodes = json_decode($data);
$inputZip = 55555;
foreach ($zipCodes as $location) {
if ($inputZip == $location->zipcode) {
echo "Success";
}
}
Can anyone tell me how I can use this search (or a better idea) to store the latitude and longitude associated with the searched zip code to two variables? I have wasted nearly my whole weekend on this so any and all help is greatly appreciated.
Also, I have no issue using the raw csv file to perform this function, I just couldn't get as far as I did with json.
Thanks everyone!
To find out the index of an array by a property of the array items, use array_column to get just the values of that column/property, then use array_search to find the index.
<?php
$inputZip = 35004;
$index = array_search($inputZip, array_column($zipCodes, 'zipcode')); // 0
print_r($zipCodes[$index]); // the entire object
https://3v4l.org/TAXQq
Based on your code:
foreach ($zipCodes as $index => $location) { // index is a key
if ($inputZip == $location->zipcode) {
echo "Index is ".$index;
break;
}
}
var_dump($zipCodes[$index]);
I should note that it seems you are doing something wrong because you don`t suppose to store your data like this and loop through array all the time.
To get the keys of an array that is filtered due to certain parameters that must be met you could use array_keys and array_filter.
For Example
$array = [1,2,1,1,1,2,2,1,2,1];
$out = array_filter($array,function($v) {
return $v == 2;
});
print_r(array_keys($out));
Output
Array
(
[0] => 1
[1] => 5
[2] => 6
[3] => 8
)
Try the above example in PHP Sandbox
To match your actual data structure.
$json = '[{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35005,"state abbreviation": "AL","latitude": 33.606579,"longitude": -86.50649,"city": "Moody","state": "Alabama"}]';
$array = json_decode($json);
$out = array_filter($array, function($v) use ($inputZip) {
return $v->zipcode == $inputZip; // for the below output $inputZip=35004
});
print_r(array_keys($out));
Output
Array
(
[0] => 0
[1] => 1
)
Try the example in PHP Sandbox

Nested Json php for loop status[0] issue

Hi I have a Json format like below:
{
"result":0,
"status":[
{
"id":"00001",
"vid":"yes"
},
{
"id":"00002",
"vid":"yes"
},
{
"id":"00003",
"vid":"no"
}
]
}
I want to use the json_decode function in PHP to decode the id values such as below:
00001
00002
00003
here is the code I am using:
$url = file_get_contents("URL");
foreach(json_decode($url, true) as $key=>$value){
foreach($value->status[0] as $key1=>$value1){
echo $value1->id;
}
}
The problem seems to be with status[0] as far as I know using status[0] is the only way to select the status key. However I can't get the loop to work correctly.
I get the error: Trying to get property of non-object meaning status[0] is not finding status in the Json array however I have no idea why this is since it works when I pull a value like:
$id = $url->status[0]->id;
If anyone has any suggestions or advice I'd greatly appreciate it. Thanks
I removed some commas from your json data.
Code: demo: https://3v4l.org/C1Mda
$json = '{"result":0,"status":[{"id":"00001"},{"id":"00002"},{"id":"00003"}]}';
foreach(json_decode($json, true)['status'] as $status){
echo $status['id'] , "\n";
}
Output:
00001
00002
00003
Because you are using json_decode's true parameter, an array is generated. You need to use square bracket syntax.
Or you can use objects:
foreach(json_decode($json)->status as $status){
echo $status->id , "\n";
}
Your JSON is invalid look { "id":"00001", }
And json_decode( $json, false ) should be.
working solution:
$json = '{
"result":0,
"status":[{"id":"00001"},
{"id":"00002"},
{"id":"00003"}
]
}';
$data = json_decode($json, false);
foreach ($data->status as $status){
echo $status->id;
}
You can just use array_column to extract the id values from the status element of your JSON (once it is corrected by removing the superfluous commas):
$ids = array_column(json_decode($json, true)['status'], 'id');
print_r($ids);
Output:
Array (
[0] => 00001
[1] => 00002
[2] => 00003
)
Demo on 3v4l.org

Convert MySQL to Json ResultSet

I'm trying to turn my results into a json encoded string. I know that now working on an external api seems a bit much, but I do think that it's something that will come in handy as times goes on. Currently, I use the following function:
//API Details
public function APIReturnMembers() {
$query = <<<SQL
SELECT uname
FROM {$this->tprefix}accounts
SQL;
$encode = array();
$resource = $this->db->db->prepare( $query );
$resource->execute();
foreach($resource as $row) {
$encode[] = $row;
}
echo json_encode($encode);
}
It does what it's supposed to as far as returning results go, e.g.:
[{"uname" : "guildemporium"}, {"uname" : "doxramos"}]
When I saw that I was ecstatic! I was on my way to implementing my own API that others could use later on as I actually got somewhere! Now of course I have hit a hickup. Testing my API.
To run the code to get the results I used
$api_member_roster = "https://guildemporium.net/api.php?query=members";
$file_contents = #file_get_contents($api_member_roster); // omit warnings
$memberRoster = json_decode($file_contents, true);
print_r($memberRoster);
The good news!
It works. I get a result back, yay!
Now the Bad.
My Result is
[
0 => ['uname' => 'guildemporium'],
1 => ['uname' => 'doxramos']
]
So I've got this nice little number integer interrupting my return so that I can't use my original idea
foreach($memberRoster as $member) {
echo $member->uname;
}
Where did this extra number come from? Has it come in to ruin my life or am I messing up with my first time playing with the idea of returning results to another member? Find out next time on the X-Files. Or if you already know the answer that'd be great too!
The numbered rows in the array as the array indices of the result set. If you use print_r($encode);exit; right before you use echo json_encode($encode); in your script, you should see the exact same output.
When you create a PHP array, by default all indices are numbered indexes starting from zero and incrementing. You can have mixed array indices of numbers and letters, although is it better (mostly for your own sanity) if you stick to using only numbered indices or natural case English indices, where you would use an array like you would an object, eg.
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
print_r($arr);
/*Array
(
[foo] => bar
[bar] => foo
)*/
$arr = [
'foo','bar'
];
/*Array
(
[0] => foo
[1] => bar
)*/
Notice the difference in output? As for your last question; no. This is normal and expected behaviour. Consumers will iterate over the array, most likely using foreach in PHP, or for (x in y) in other languages.
What you're doing is:
$arr = [
['abc','123']
];
Which gives you:
Array
(
[0] => Array
(
[0] => abc
[1] => 123
)
)
In order to use $member->foo($bar); you need to unserialize the json objects.
In you api itself, you can return the response in json object
In your api.php
function Execute($data){
// Db Connectivity
// query
$result = mysqli_query($db, $query);
if( mysqli_num_rows($result) > 0 ){
$response = ProcessDbData($result);
}else{
$response = array();
}
mysqli_free_result($result);
return $response;
}
function ProcessDbData($obj){
$result = array();
if(!empty($obj)){
while($row = mysqli_fetch_assoc($obj)){
$result[] = $row;
}
return $result;
}
return $result;
}
function Convert2Json($obj){
if(is_array($obj)){
return json_encode($obj);
}
return $obj;
}
Calling api.php
$result = $this->ExecuteCurl('api.php?query=members');
print_r($result);
here you $result will contain the json object

How to change the array in order to make the desired JSON object in PHP?

I've an array titled $request as follows :
Array
(
[invite_emails] => suka#gmail.com, swat#gmail.com
[page_id] => 322
[ws_url] => http://app.knockknot.com/api/group/sendInvitation
)
After using json_encode($request) I got following output:
{
"invite_emails": "suka#gmail.com, swat#gmail.com",
"page_id": "322",
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
But actually I want the JSON object as follows :
{
"page_id": 322,
"invite_emails": [
"suka#gmail.com",
"swat#gmail.com"
],
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
How should I manipulate the array in PHP in order to get the above desired JSON object?
Please someone help me.
Split the list of emails using the comma:
$array["invite_emails"] = preg_split("#\s*,\s*#", $array["invite_emails"]);
I personally prefer using callback functions for readability and possibilities. To your purpose, array_walk should fit:
<?php
// reproducing array
$request = array(
"invite_emails" => "suka#gmail.com, swat#gmail.com",
"page_id" => 322,
"ws_url" => "http://app.knockknot.com/api/group/sendInvitation"
);
// callback finds a comma-separated string and explodes it...
array_walk($request, function (&$v,$k) {if ($k == 'invite_emails') $v = explode(", ", $v);});
// ... and then encode it to JSON
json_encode($request);
// testing
print_r($request);
OUTPUT:
{
"invite_emails":[
"suka#gmail.com",
"swat#gmail.com"
],
"page_id":322,
"ws_url":"http://app.knockknot.com/api/group/sendInvitation"
}
You are free to change the field if your needs changes, and even suppress it to be used with any field of the array.
Use PHP explode for example:
$array['invite_emails'] = explode(',',$array['invite_emails']);
To avoid spaces use preg_split (source):
$array['invite_emails'] = preg_split("/[\s,]+/", $array['invite_emails']);
This entry:
[invite_emails] => suka#gmail.com, swat#gmail.com
should be an array (currently, it is a string) in PHP, then in JSON it will look like you want it.

Retrieve value from a Json Array

I'm having difficulty in retrieving values from a Json array. I have a Json dataset that has been created using json_encode. This is how it appears after using json_decode and displaying using print_r:
Array ( [0] => stdClass Object ( [postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca... ) ) a_post_data_array = 1
The code that achieves this is as follows:
$post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy";
$post_data_response = file_get_contents($post_data_URL);
$a_post_data_array=json_decode($post_data_response);
I now simply need to retrieve some of the values from this array to use as variables. The array will only ever have 1 set of values. I'm using the following code but it isn't working.
echo "**** -- " . $a_post_data_array[post_title] . "<br>";
Can anyone please help? I'm sorry this is so basic. I've been searching online but can't find any examples of this.
There are multiple issues with your code:
First you should instruct json_decode to give you a pure array with $data = json_decode($response, TRUE);
Then the result array is a list, and you have to access the first element as $data[0]
The entry you want to access has the key postTitle, not post_title as your example code showed. (And unless that's a predefined constant won't work.)
And you need to put those array keys in quotes, like print $data[0]["postTitle"];
Turn up your error_reporting level for some development help.
echo "** -- " . $a_post_data_array[0]['post_title'];
try this PHP code:
//$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json");
//$PersonObject = json_decode($post_data_response);
// Get Person Object from JSON Source
$PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}');
// Get data from Object
echo "Person ID => $PersonObject->ID<br>";
echo "Person Name => $PersonObject->firstname<br>";
echo "Person Lastname => $PersonObject->lastname<br>";
echo "Person Age => $PersonObject->age<br>";
echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";

Categories