I'm trying to make a script that redirects to a random YouTube video. How would I take the vidKey, put each $vidkey in an array and then randomize that array so you get redirected to a different YouTube video?
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
foreach ($sxml->entry as $entry) {
$vidKey = substr(strrchr($entry->id,'/'),1);
}
Put each key into an array, then shuffle it when you're done:
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
$vidKeys = array();
foreach ($sxml->entry as $entry)
$vidKeys[] = substr(strrchr($entry->id,'/'),1);
shuffle($vidKeys);
Then just pick one entry from it, like $vidKeys[0].
You could also put the results in the database and ORDER BY RAND(). On next request you get the video keys from the DB, select and remove an entry from the list (see array_shift) and put the list back in the DB. You do this until there are no more video keys, then fire the google query again and so on... This saves your script from querying Google on each page load, and decreases the chances for being redirected to the same video
$i=0; $random_video = mt_rand(1, 25);
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
foreach ($sxml->entry as $entry) {
if($random_video==$i++){
$vidKey = substr(strrchr($entry->id,'/'),1); break;
}
}
PHP has a built-in function for selecting a random element (or elements) from an array, array_rand()
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
$vidKeys = array();
foreach ($sxml->entry as $entry)
$vidKeys[] = substr(strrchr($entry->id,'/'),1);
$randomVidKey = $vidKeys[array_rand($vidKeys)];
Related
I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.
I have an array with three indexes which themselves are arrays:
$array['title'];
$array['description'];
$array['link'];
I need to add to this array in a loop.
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array = $information['processed'];
}
The above works fine when I do it once without the loop, however I cannot add to $array.
What I have tried is:
$array = array();
$arraytemp = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$arraytemp = $information['processed'];
$array = $array + $arraytemp; // the unique append as outlined in php manual
}
I have also tried:
$array = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array[] = $information['processed'];
}
And I have also tried:
$array = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
array_push($array,$information['processed']);
}
For the application I am developing, I need a way of adding to this array whilst reserving the key structure. So I want to add the new information to the end of the array.
Creating a new dimension by doing something like the following is not appropriate for my program:
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array[$i] = $information['processed'];
}
//The above is not appropriate for my application
Any ideas?
Thanks guys.
$array = array();
for ($i=0;$i<10;$i++)
{
$array[$i] = $information['processed'];
}
I Select * From my sql table in PHP, and I convert it to JSON, so the results are like this:
([
{"id":"350","Name":"BlaBla","Info":"BlaBla"},
{"id":"351","Name":"BlaBla","Info":"BlaBla"},
{"id":"352","Name":"BlaBla","Info":"BlaBla"}
]);
I scrape a clients website for images (this is a request of the client) based on the id in the records above, and I output images into a similar array/dictionary and output into JSON:
([
{"image1":"http://Sourceofimg.jpg"},
{"image2":"http://Sourceofimg.jpg"},
{"image3":"http://Sourceofimg.jpg"},
{"image4":"http://Sourceofimg.jpg"},
{"image5":"http://Sourceofimg.jpg"}
]);
So lets say I scrape a page, page.php?id=350, I'd get a similar output to the image array above, how can I append/add that result to the first array where id=350?
EDIT
This is where I would like to combine the arrays:
while ($row = mysql_fetch_assoc($results))
{
$rows[] = $row;
$url = 'http://www.url.com/page.php?id='.$row['id'].'';
$html = file_get_html($url);
foreach($html->find('div.classvalue') as $element){
foreach($element->find('img') as $img){
$images[] = array("image".$i."" => $img->src);
$i = $i + 1;
$rows = array_merge($rows, $images);
} } }
My version clearly does not work, it seems to be appending new images to the already existing image[] therefore the last element of $rows[] will get the full list of images, where I just want the images tied in with that id.
Also by merging, it does not merge correctly I get an output like this e.g:
([
{"id":"350","Name":"BlaBla","Info":"BlaBla"},
{"image1":"http://Sourceofimg.jpg"},
{"image2":"http://Sourceofimg.jpg"},
{"id":"351","Name":"BlaBla","Info":"BlaBla"}
]);
I would like it like:
([
{"id":"350","Name":"BlaBla","Info":"BlaBla", "image1":"http://Sourceofimg.jpg", "image2":"http://Sourceofimg.jpg"} etc...
]);
I think this is what you need. You first have to start with a clean $images array using $images = array(); so you won't have the results of previous loops in your array. Then you should collect the images inside the $images array (using the forloops). Then you can store the images in the $row array under the key 'images' using $row['images'] = $images;.
Hope this is what you need.
while ($row = mysql_fetch_assoc($results)) {
$url = 'http://www.url.com/page.php?id='.$row['id'].'';
$html = file_get_html($url);
$images = array();
$i = 0;
foreach($html->find('div.classvalue') as $element){
foreach($element->find('img') as $img){
$row["image".$i] = $img->src;
$i = $i + 1;
}
}
$rows[] = $row;
}
On php side use array_merge() with both arrays. In addition array_unique will become handy (it will remove duplicates).
You have to add $images to the actual row. What you are doing, is resizing array.
$actualIndex = count($rows);
$rows[] = $row;
...
...
$rows[$actualIndex] = $images;
Or something like this
You can tweak $rows[$actualIndex] to satisfy your structure.
First set somewhere $imageID = 1;
$rows[$actualIndex]['image'.$imageID] = $images['url']
imageID++;
What I have here is a PHP page working with the Facebook API.
What I'm trying to do is (after permissions are set by the user), to get the user's friends' user IDs via: $facebook->api('/me/friends'). The problem is, I would only like to get random 10 friends. I could easily limit results to 10 by using /me/friends?limit=10, but then again that wouldn't be random.
So here is what I have right now:
$friendsLists = $facebook->api('/me/friends');
function getFriends($friendsLists){
foreach ($friendsLists as $friends) {
foreach ($friends as $friend) {
// do something with the friend, but you only have id and name
$id = $friend['id'];
$name = $friend['name'];
shuffle($id);
return "#[".$id.":0],";
}
}
}
$friendsies = getFriends($friendsLists);
$message = 'I found this Cover at <3 '.$Link.'
'.$friendsies.' check it out! :)';
I have tried shuffle(), and the first option from here: https://stackoverflow.com/a/1656983/1399030, but I think I could be doing something wrong because they don't return anything. I'm pretty sure I'm close, but what I've tried so far is not working. Can it be done?
you'll want to use the shuffle before you foreach, so that you actually shuffle the array.
after that, you'll want to limit to 10 friends. I'd suggest adding an $i var to count to ten, and adding to a new array.
Something like this:
function getFriends($friendsLists){
$formatted_friends = array();
$i = 0;
foreach ($friendsLists as $friends) {
// I'm guessing we'll need to shuffle here, but might also be before the previous foreach
shuffle($friends);
foreach ($friends as $friend) {
// do something with the friend, but you only have id and name
// add friend as one of the ten
$formatted_friends[$i] = $friend;
// keep track of the count
$i++;
// once we hit 10 friends, return the result in an array
if ($i == 10){ return $formatted_friends; }
}
}
}
keep in mind though that it'll return an array and not a string that you can use in an echo. If you want, you can put this in an echo for debugging purposes:
echo 'friends: '.print_r($friendsies, true);
I am parsing data from a website via xml that always changes so I do not know what data to search for, just the location. I get the data by calling upon the specific class for the data needed. Within this class that is retrieved, there are only certain things I need retrieved. So for example, I retrieve the class .candy. Now .candy corresponds to different parts on the website so let us say that candy retrieves "Cookies Chocolate gummy bear". I only want "chocolate".
My idea was to put everything into an array an array and then access it. Assume the array is called test, then I would want to access "chocolate" by $test[1];
It is not working for me (says array is out of bounds whenever I put a number bigger than 0) and I was wondering if anyone knows where my mistake is within my code? Please note that the above was purely an example for better understanding and not the actually data I need.
Thank you
function getData($html)
{
#$doc=new DOMDocument();
#$doc->loadHTML($html);
$xml=simplexml_import_dom($doc); // just to make xpath more simple
//$images=$xml->xpath('//[]');
$info=$xml->xpath('//*[#class="date"]');
$arr= array();
foreach ($info as $img) {
$arr= array($img);
}
return $arr[3];
}
You are replacing $arr in every loop. $arr[] = $img; should work.
Example:
function getData($html)
{
#$doc = new DOMDocument();
#$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);
$info = $xml->xpath('//*[#class="date"]');
$arr = array();
foreach ($info as $img)
{
$arr[] = $img;
}
return $arr[3];
}
foreach ($info as $img) {
$arr[] = $img;
}