$likes = $facebook->api("/me/likes");
foreach($likes['data'] as $page_likes) {
if($page_likes['id'] == "someid") {
}
}
Is there any simple way to find it instead of looping those hundreds, thousands likes?
Best method (to answer questions like this): Read documentation …!
https://developers.facebook.com/docs/reference/api/user/#likes:
“You can check if a User likes a specific page by issuing an HTTP GET to /PROFILE_ID/likes/PAGE_ID. […] This will return, in the data array, an object with the following fields if the user is connected to the page: […] If the user is not connected to the page, the data array will be empty.”
array_map or array_walk might be more efficient, but it depends on what you want to do with the data...
Related
So I have done some searching but the results seems to be kind of scrambled, that's why I'm asking here.
The problem is that I have a setup.php file, in which I preload the options that are needed to load some things in the page, and I don't know if this is the best method.
Here is the code:
function fetch_site_option($id){
$conn=Core::getInstance()->db->prepare("SELECT value FROM options WHERE id = ?");
$conn->bindParam(1,$id,PDO::PARAM_INT);
$conn->execute();
if($conn->rowCount()==1){
$data=$conn->fetch(PDO::FETCH_ASSOC);
}else{
$data=null;
}
return $data['value'];
}
and the values that need to be retrieved:
$siteTitle=fetch_site_option('1');
$mainPage=fetch_site_option('2');
$debug=fetch_site_option('3');
$logo=fetch_site_option('4');
$sTT=fetch_site_option('5');
This repeats a lot of times, and that's why it needs to be very efficient.
Thanks in advance.
To be more efficient, you should try to merge your multiple requests into one. Try something like this:
SELECT id, value FROM options WHERE id IN (?,?,?,?,?)
This will return all required rows in one request. Instead of returning one value at a time, you should change the function fetch_site_option() to return an array of ids and values.
I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...
OK, here's my dilemma:
I've read all over about how many guys want to be able to display a set of images from Flickr using PHPFlickr, but lament on how the API for PhotoSets does not put individual photo descriptions. Some have tried to set up their PHP so it will pull the description on each photo as the script assembles the gallery on the page. However, the method has shown how slow and inefficient it can be.
I caught an idea elsewhere of creating a string of comma separated values with the photo ID and the description. I'd store it on the MySQL database and then call upon it when I have my script assemble the gallery on the page. I'd use explode to create an array of the photo ID and its description, then call on that to fill in the gaps...thus less API calls and a faster page.
So in the back-end admin, I have a form where I set up the information for the gallery, and I hand a Set ID. The script would then go through and make this string of separated values ("|~|" as a separation). Here's what I came up with:
include("phpFlickr.php");
$f = new phpFlickr("< api >");
$descArray = "";
// This will create an Array of Photo ID from the Set ID.
// $setFeed is the set ID brought in from the form.
$photos = $f->photosets_getPhotos($setFeed);
foreach ($photos['photoset']['photo'] as $photo) {
$returnDesc = array();
$photoID = $photo['id'];
$rsp = $f->photos_getInfo($photoID);
foreach ($rsp as $pic) {
$returnDesc[] = htmlspecialchars($pic['description'], ENT_QUOTES);
}
$descArray .= $photoID."|~|".$returnDesc[0]."|~|";
}
The string $descArray would then be placed in the MySQL string that puts it into the database with other information brought in from the form.
My first question is was I correct in using a second foreach loop to get those descriptions? I tried following other examples all over the net that didn't use that, but they never worked. When I brought on the second foreach, then it worked. Should I have done something else?
I noticed the data returned would be two entries. One being the description, and the other just an "o"...hence the array $returnDesc so I could just get the one string I wanted and not the other.
Second question is if I made this too complicated or not. I like to try to learn to write cleaner/leaner code, and was looking for opinions.
Suggestions on improvement are welcome. Thank you in advance.
I'm not 100% sure as I've just browsed the source for phpFlickr, and looked the the Flickr API for the getInfo() call. But let me have a go anyway :)
First off, it looks like you shouldn't need that loop, like you mention. What does the output of print_r($rsp); look like? It could be that $rsp is an array with 1 element, in which case you could ditch the inner loop and replace it with something like $pic = $rsp[0]; $desc = $pic['description'];
Also, I'd create a new "description" column in your database table (that has the photo id as the primary key), and store the description in their on its own. Parsing db fields like that is a bit of a nightmare. Lastly, you might want to force htmlspecialchars to work in UTF8 mode, cause I don't think it does by default. From memory, the third parameter is the content encoding.
edit: doesn't phpFlickr have its own caching system? Why not use that and make the cache size massive? Seems like you might be re-inventing the wheel here... maybe all you need to do is increase the cache size, and make a getDescription function:
function getDescription ($id)
{
$rsp = $phpFlickr->photos_getInfo ($id);
$pic = $rsp[0];
return $pic['description'];
}
I'm working on a patch to submit to the Registration Code module for Drupal. In short, is there a more efficient way to write the code below?
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', array('regform' => 'regform'));
if (empty($cnfg['regform'])) {
return;
}
}
It seems like I should be able to reduce it to one if statement with && combining two conditions, but I haven't found the syntax or the necessary php array function that would allow me to do that.
In case some context helps, the regcode_voucher sub-module allows users to enter their registration code on the user edit page. On our sites, after a "beta" period, we want to simplify the registration form by removing the registration code field; but we'd like users to still be able to enter the code on their account edit page. The code above is part of a patch that allows the regcode's hook_user changes to be bypassed.
Code looks like good, what efficient do you want? Little changes may be:
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', null);
if ($cnfg) {
// do your actions
}
}
And I don't recommend to merge if..., code should be clear and simpler to understand. If you merge these for optimizing, you win "tiny" milliseconds for real-live processors, but lost your clean code.
Why are you returning an array from variable_get if the variable is not found? variable_get will always return a string or a serialized array (that needs to be unserialized). If I'm missing something, you can use array_key_exists('regcode', variable_get(...)) to check for the array key.
This should work... note returning "false" from variable_get as a default if the variable is not found, which will cause the if conditions to not match. I personally find this more readable than nested if statements (for 3+ conditions I'd nest, though).
if( module_exists('regcode_voucher') && variable_get('regcode_voucher_display', false) ) {
// stuff
}
I have created a small search and filter form with a POST action in controller/index, which POSTs to itself the conditions and fields to paginate ($this->paginate($conditions)).
That is good for the first page, however on the subsequent pages the filter conditions are lost. Pagination passedArgs supports GET variables well.
Are there an un-complex ways to pass the POST conditions to the other paginated pages?
The method I have looked at is to pass the $conditions via the session, which isn't without complexity of assigning the session and unsetting the session on submitting the form again (more refinements to the filter criteria by the user).
The other method is passing the $conditions as serialized string with url_encode as a GET parameter.
Is there a good 'cake' way to do this more like passedArgs. Sessions and url_encode do not look like cake style.
Thanks
Is there an un complex way to pass the
post conditions to the other paginated
pages?
Nope.
Is there an good cake way to do this
more like passArgs, sessions and url
encode do not look like cake style.
There is only one way, no matter, cake or not cake.
Search must be done using GET method.
Parameters being passed via QUERY STRING.
So, make your search form with method="GET" and then use http_build_query() to assemble a query string and use it to make links to other pages.
Being a little curious, you can see an example right here on SO:
http://stackoverflow.com/questions/tagged?tagnames=php&page=5&sort=newest&pagesize=50
You can use passedArgs.
in the method controller :
if ( empty($this->passedArgs['search']) ){
$this->passedArgs['search'] = $this->data['YourModel']['search'];
}
if ( empty($this->data) ){
$this->data['YourModel']['search'] = $this->passedArgs['search'];
}
in your view :
$this->Paginator->options(array('url' => $this->passedArgs));
If it was me I would run with your idea of saving the stuff into the session. Then I would add a page dimension to the session, to store each page, thus allowing users to go back and forth with ease.
$this->Session->write('Search.page.1.params',$params);
$this->Session->write('Search.page.2.params',$params2);
In order to do it in a Cake way, you'd probably want to write your own Pagination helper, or plugin. Which you could then use more effectivly in your controllers as
$this->MyPages->paginate('MyModel');
I suppose, this functionality would also give you the option to allow your users to 'Save my search' if they wanted to, as you could dump the session params into a SavedSearch model or similar.
Don't forget to $this->Session->destroy() before starting a new search though!
You can also use the Post/Redirect/Get design pattern pattern to solve this, allowing users to bookmark URLs of searches (without them expiring as a session would) and keeping URLs looking friendly. For example:
function index($searchTerms = null) {
// post/redirect/get
if (isset($this->data['SearchForm'])) {
$this->redirect(array($this->data['SearchForm']['search_terms']));
}
// your normal code here.
}
The search form data POSTs to /controller/action but the user is redirected and instead GETs /controller/action/search+terms where the terms are passed into the action as a parameter (ie. $searchTerms).
If you simply change the form submission method to GET you will instead see something like: /controller/action?data[SearchForm][search_terms]=search+terms
Thanks Deizel for the POST / REDIRECT / GET pattern.
I implemented the GET method of posting data.
For pagination used this
$urlparams = $this->params['url'];unset($urlparams['url']);
$paginator->options(array('url' => array('?' => http_build_query($urlparams))));
We had multi checkboxes and the naming convention used where :
foreach ($checkboxes as $chbox ) {
// used variable variables to generate the data grid table based on selected fields
${'_field'.$chbox} = (isset($this->params['url']['displayfields'][$chbox])?$this->params['url']['displayfields'][$chbox]:1);
$options = array('label'=>$chbox,'type'=>'checkbox','value'=> ${'_field'.$chbox});
if ( ${'_field'.$chbox} ) $options['checked'] = 'checked';
echo $form->input('Filter.displayfields['.$chbox.']',$options);
In the post method the naming convention for the checkboxs would be Filter.displayfields.checkbox name
This helps in getting an array either in $this->data or $this->params['url']
There should be an persistent pagination plugin/component for cakePHP would make life much more easier and fun to develop with cakePHP.
Thanks all.