sort json facebook data - facebook

i'm trying to figure out how to sort the json data provided by a facebook events feed.
This is the code I've been using
$int_count = 1;
$FBpage = file_get_contents('https://graph.facebook.com/demo/events?access_token=170978966368624|vNXbO1MPwpvP56jU6zWGCyRESQ');
$FBdata = json_decode($FBpage);
foreach ($FBdata->data as $events )
{
$x_sdt = explode("T",$events->start_time);
$x_sd = explode("-",$x_sdt[0]);
if($x_sdt[0] > date("Y-m-d"))
{
$StatusID = explode("_", $events->id);
echo '<ul class="shows">';
echo '<li class="date">';
echo $x_sd[2]."/".$x_sd[1]."/".$x_sd[0];
echo '</li>';
echo '<li class="title">'.maxTruncate($events->name, 62).'</li>';
echo '</ul>';
}
$int_count++;
if($int_count==5){ break; }
}
Can anyone point me in the right direction, so far I beleive i should be using usort(), but when I look at tutorials i've got no idea what the go is. any bombs of wisdom would be greatly appreciated.
Thanks
Frank

With usort, you just have to write your own little comparison function, that gets two of the arrays elements as parameters, compares them by whatever metric you like, and returns a value saying which one is supposed to be considered “greater” than the other.
Have a look at the examples in the PHP manual, it’s really quite easy.
If you still can’t get it to work on your own, then please describe what you tried and on what (example) data structure.

Related

Symfony2 - Setting up a blog archive

I've been working on trying to setup a blog archive for a blog site where the use clicks on a date and the corresponding posts appear. (see image) I understand I need to retrieve all my blog posts and sort by date, but the steps after that are foggy to me. Taking that data then sorting it by month/year and passing it to a template is the part I am having trouble with.
Can someone shed some light on what I am doing wrong or provide a simple working example?
What I have thus far:
public function archiveAction()
{
$em = $this->getDoctrine()->getManager();
// $query = $em->getRepository('AcmeProjectBundle:Blog')
// ->findAll();
$blogs = $em->getRepository('AcmeProjectBundle:Blog')
->getLatestBlogs();
if (!$blogs) {
throw $this->createNotFoundException('Unable to find blog posts');
}
foreach ($blogs as $post) {
$year = $post->getCreated()->format('Y');
$month = $post->getCreated()->format('F');
$blogPosts[$year][$month][] = $post;
}
// exit(\Doctrine\Common\Util\Debug::dump($month));
return $this->render('AcmeProjectBundle:Default:archive.html.twig', array(
'blogPosts' => $blogPosts,
));
}
You want to tell your archiveAction which month was actually clicked, so you need to one or more parameters to it: http://symfony.com/doc/current/book/controller.html#route-parameters-as-controller-arguments (I would do something like /archive/{year}/{month}/ for my parameters, but it's up to you.) Then when someone goes you myblog.com/archive/2014/04, they would see those posts.
Next, you want to show the posts for that month. For this you'll need to use the Doctrine Query builder. Here's one SO answer on it, but you can search around for some more that pertain to querying for dates. Select entries between dates in doctrine 2

WWW::Mechanize::Firefox looping though links

I am using a foreach to loop through links. Do I need a $mech->back(); to continue the loop or is that implicit.
Furthermore do I need a separate $mech2 object for nested for each loops?
The code I currently have gets stuck (it does not complete) and ends on the first page where td#tabcolor3 is not found.
foreach my $sector ($mech->selector('a.link2'))
{
$mech->follow_link($sector);
foreach my $place ($mech->selector('td#tabcolor3'))
{
if (($mech->selector('td#tabcolor3', all=>1)) >= 1)
{
$mech->follow_link($place);
print $_->{innerHTML}, '\n'
for $mech->selector('td.dataCell');
$mech->back();
}
else
{
$mech->back();
}
}
You cannot access information from a page when it is no longer on display. However, the way foreach works is to build the list first before it is iterated through, so the code you have written should be fine.
There is no need for the call to back as the links are absolute. If you had used click then there must be a link in the page to click on, but with follow_link all you are doing is going to a new URL.
There is also no need to check the number of links to follow, as a for loop over an empty list will simply not be executed.
To make things clearer I suggest that you assign the results of selector to an array before the loop.
Like this
my #sectors = $mech->selector('a.link2');
for my $sector (#sectors) {
$mech->follow_link($sector);
my #places = $mech->selector('td#tabcolor3');
for my $place (#places) {
$mech->follow_link($place);
print $_->{innerHTML}, '\n' for $mech->selector('td.dataCell');
}
}
Update
My apologies. It seems that follow_link is finicky and needs to follow a link on the current page.
I suggest that you extract the href attribute from each link and use get instead of follow_link.
my #selectors = map $_->{href}, $mech->selector('a.link2');
for my $selector (#selectors) {
$mech->get($selector);
my #places = map $_->{href}, $mech->selector('td#tabcolor3');
for my $place (#places) {
$mech->get($place);
print $_->{innerHTML}, '\n' for $mech->selector('td.dataCell');
}
}
Please let me know whether this works on the site you are connecting to.
I recommend to use separate $mech object for this:
foreach my $sector ($mech->selector('a.link2'))
{
my $mech = $mech->clone();
$mech->follow_link($sector);
foreach my $place ($mech->selector('td#tabcolor3'))
{
if (($mech->selector('td#tabcolor3', all=>1)) >= 1)
{
my $mech = $mech->clone();
$mech->follow_link($place);
print $_->{innerHTML}, '\n'
for $mech->selector('td.dataCell');
#$mech->back();
}
# else
# {
# $mech->back();
# }
}
I am using WWW:Mechanize::Firefox to loop over a bunch of URLs with loads of Javascript. The page does not render immediately so need test if a particular page element is visible (similar to suggestion in Mechanize::Firefox documentation except 2 xpaths in the test) before deciding next action.
The page eventually renders a xpath to 'no info' or some wanted stuff after about 2-3 seconds. If no info we go to next URL. I think there is some sort of race condition with both xpaths not existing at once causing the MozRepl::RemoteObject: TypeError: can't access dead object error intermittently (at the sleep 1 in the loop oddly enough).
My solution that seems to work/improve reliability is to enclose all the $mech->getand$mech->is_visible in an eval{}; like this:
eval{
$mech->get("$url");
$retries = 15; #test to see if element visible = page complete
while ($retries-- and ! $mech->is_visible( xpath => $xpath_btn ) and ! $mech->is_visible( xpath => $xpath_no_info )){
sleep 1;
};
last if($mech->is_visible( xpath => $xpath_no_info) ); #skip rest if no info page
};
Others might suggest improvements on this.

How to add two numbers in sugar crm

I made module addition and in this made three fields amount1_c, amount2_c and total_amount_c to add the two numbers and display the result in the third field. I done coding in the logic looks here is my code
<?
$hook_version = 1;
$hook_array = Array();
$hook_array['before_save'] = Array();
$hook_array['before_save'][] = Array(1,'calculate_field', 'custom/modules/cases/LogicHookMath.php','LogicHookMath', 'calculate_field');
?>
and made one more file logic hook math. here is my code for
<?php
class LogicHookMath {
function calculate_field(&$bean, $event, $arguments) {
$field1 = $bean->amount1_c;
$field2 = $bean->amount2_c;
$field3 = $field1 + $field2;
$bean->amount_total_c = $field3;
}
}
?>
but still i did not get any result. Please help me out for this.
The code looks correct.
Some common "mistakes" when custom logic hooks are not working:
Make sure, the custom logic hook has the correct name (LogicHookMath.php)
Make sure, that the $bean variable is prefixed with &, so the variable is passed as a reference
Make sure the logic_hooks.php and the LogicHookMath.php files are readable by the web server user
The entire custom directory should also be writeable for the web server user
If the above does not help, try logging the progress to the sugarcrm.log using $GLOBALS['log']->info( "Value 3: ". $field3); in the custom logic hook.

How to get zend_lucene and zend_paginator to work

I've been using Zend Framework for a few months now. So, my knowledge is pretty good but I'm not quite an expert yet. I am trying to use zend_lucene with zend_paginator and so far not successful. I am able to use zend_lucene and index data successfully by itself and able to do use zend_paginator when querying the database, but I can't seem to combine the two. Here is a sample of what I am doing:
try {
$searchresults = $index->find($lucenequery);
}
catch (Zend_Search_Lucene_Exception $e) {
echo "Unable {$e->getMessage()}";
}
$page = $this->_getParam('page',1);
$paginator = Zend_Paginator::factory($searchresults);
$paginator->setItemCountPerPage(20);
$paginator->setCurrentPageNumber($page);
$this->view->paginator = $paginator;
Is there a different step I need to do with lucene and zend_paginator? I am really uncertain. The result I get is that for the first page results display properly. But when I hit the second page or third my results are blank. So uncertain what might be wrong as I can't find docs or tutorials in using the two together. Any help would be greatly appreciated.
I think this may work with the iterator adapter:
public function searchAction() {
$index = Zend_Search_Lucene::open('/path/to/lucene');
$results = $index->find($this->_getParam('q'));
$paginator = Zend_Paginator::factory($results);
$paginator->setCurrentPageNumber($this->_getParam('page', 1));
$paginator->setItemCountPerPage(10);
$this->view->results = $paginator;
}
Perhaps the problem you are having is that $paginator doesn't know how many search results there are..
So you may need to do that manually:
$paginator->setDefaultPageRange($results->count());

Youtube API - How to limit results for pagination?

I want to grab a user's uploads (ie: BBC) and limit the output to 10 per page.
Whilst I can use the following URL:
http://gdata.youtube.com/feeds/api/users/bbc/uploads/?start-index=1&max-results=10
The above works okay.
I want to use the query method instead:
The Zend Framework docs:
http://framework.zend.com/manual/en/zend.gdata.youtube.html
State that I can retrieve videos uploaded by a user, but ideally I want to use the query method to limit the results for a pagination.
The query method is on the Zend framework docs (same page as before under the title 'Searching for videos by metadata') and is similar to this:
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setTime('today');
$query->setMaxResults(10);
$videoFeed = $yt->getUserUploads( NULL, $query );
print '<ol>';
foreach($videoFeed as $video):
print '<li>' . $video->title . '</li>';
endforeach;
print '</ol>';
The problem is I can't do $query->setUser('bbc').
I tried setAuthor but this returns a totally different result.
Ideally, I want to use the query method to grab the results in a paginated fashion.
How do I use the $query method to set my limits for pagination?
Thanks.
I've decided just to use the user uploads feed as a way of getting pagination to work.
http://gdata.youtube.com/feeds/api/users/bbc/uploads/?start-index=1&max-results=10
If there is a way to use the query/search method to do a similar job would be interesting to explore.
I basically solved this in the same way as worchyld with a slight twist:
$username = 'ignite';
$limit = 30; // Youtube will throw an exception if > 50
$offset = 1; // First video is 1 (silly non-programmers!)
$videoFeed = null;
$uploadCount = 0;
try {
$yt = new Zend_Gdata_YouTube();
$yt->setMajorProtocolVersion(2);
$userProfile = $yt->getUserProfile($username);
$uploadCount = $userProfile->getFeedLink('http://gdata.youtube.com/schemas/2007#user.uploads')->countHint;
// The following code is a dirty hack to get pagination with the YouTube API without always starting from the first result
// The following code snippet was copied from Zend_Gdata_YouTube->getUserUploads();
$url = Zend_Gdata_YouTube::USER_URI .'/'. $username .'/'. Zend_Gdata_YouTube::UPLOADS_URI_SUFFIX;
$location = new Zend_Gdata_YouTube_VideoQuery($url);
$location->setStartIndex($offset);
$location->setMaxResults($limit);
$videoFeed = $yt->getVideoFeed($location);
} catch (Exception $e) {
// Exception handling goes here!
return;
}
The Zend YouTube API seems silly as the included getUserUploads method never returns the VideoQuery instance before it actually fetches the feed, and while you can pass a location object as a second parameter, it's an "either-or" situation - it'll only use the username parameter to construct a basic uri or only use the location, where you have to construct the whole thing yourself (as above).