Looping code using PHP - php

I am currently using YouTube's API JSON-C response to pull data from a playlist and display the content in a list. I am doing this using PHP, however because YouTube restricts the maximum number of videos called, I have a hit a stumbling block. The maximum I can request is 50 whereas I have over 200 videos which I need to put in a list and I want to be able to do this dynamically.
I understand that I will have to loop the response, which is what I have done but is there a way it can be dynamically done?
If you could help me that would be great, my code is:
$count = 0;
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
if($count == 50) {
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=50&max-results=50&v=2&alt=jsonc";
$data = file_get_contents($query);
if($data){
$data = json_decode($data);
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
}
}
}
if($count == 100) {
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=100&max-results=50&v=2&alt=jsonc";
$data = file_get_contents($query);
if($data){
$data = json_decode($data);
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
}
}
}
}
and so on...
If you could help me out, or at least point me in the right direction that would be great, thanks.

One way is to loop over requests, and then over each item in the request. Like this:
$count = 1;
do {
$data = ...; // get 50 results starting at $count
foreach ($data->items as $item) {
echo "$count {$item->id} - {$item->title}<br />\n";
$count++;
}
} while (count($data->items) == 50);
Note that start-index is 1-based, so you have to query for 1, 51, 101 etc.
(This is actually quite similar to reading a file through a buffer, except with a file you've reached the end if the read gives you 0 bytes, while here you've reached the end if you get less than the amount you asked for.)

What I would do is first call the 4 pages, and then combine the results into 1 single array, then iterate over the data.
$offsets = array(0,50,100,150);
$data = array();
foreach($offsets as $offset)
{
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=" . $offset . "&max-results=50&v=2&alt=jsonc";
$set = file_get_contents($query);
if(!emprty($set ))
{
$data = array_merge($data,json_decode($set));
}
}
//use $data here

Related

Multiple json in one foreach

Hey i have five json from all getting information now i encountered with problem like this -> from five different json i need to get latest videoId who newer shows first and all it need put to one function foreach for my too hard i try it do about 5hours and stay in same step
Json 1 json 2
All code need from this two json get latest(newest) videoId in one foreach echo
<?php
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$i = 0;
foreach($videoList1->items as $item){
if(isset($item->id->videoId)) {
echo $item->id->videoId;
if ( ++$i > 3) {
break;
}
}
}
Tray this:
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList = array_merge($videoList1["items"],$videoList2["items"]);
/// sort lastet first
foreach ($videoList as $key => $part) {
$sort[$key] = strtotime($part['snippet']['publishedAt']);
}
array_multisort($sort, SORT_DESC, $videoList);
foreach ($videoList as $video) {
if(isset($video["id"]["videoId"])) {
echo 'publishedAt: '. $video['snippet']['publishedAt'] . ' VideoID: ' . $video["id"]["videoId"] . "\n </br>";
}
}

PHP trying to add values to an array in a while loop

I want to pull rows from the database, attach a value to those rows, then order those rows based on a value. The problem is that in trying to do this via the while loop I get an error:
"Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in
C:\xampp\htdocs\productivitysuite\index.php on line 98"
My goal is to retrieve rows from a database and organize those rows based on a value I calculate in PHP php ($priority), then display certain values of those rows based on their priority. The problem is that I get this darn error and I don't know why, nor do I know where to look for help to resolve it! Hopefully SO can help diagnose this.
code:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE";
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
$nowDate = date("m/d/Y");
$D = 1 / (date_diff($row['dueDate']- $nowDate));
//Activity category multiplier
if($row['taskType'] == "Daily"){
$C = 0.5;
} elseif($row['taskType'] == "Maintenance"){
$C = 0.2;
} elseif ($row['taskType'] == "School_Study") {
$C = 0.75;
} elseif ($row['taskType'] == "Personal_Project") {
$C = 0.80;
} elseif ($row['taskType'] == "Work_Project") {
$C = 0.65;
}
$U = ($C - (1 / $D))* $E; //urgency rating; SET PER ROW!
$I = $row['importance']; //Importance rating
$priority = $U + $I;
$results[] = ($row => $priority);
//The array
$priorityOutput = $priorityRow.$counter;
++$counter;
echo "<tr><td>";
echo $row['taskName'];
echo "</td><td>";
echo $row['taskType'];
echo "</td><td>";
echo $row['dueDate'];
echo "</td></tr>";
//Make the below its own loop where I output in order of decreasing UI value
}
//now we have an array of key => value pairs with rows tied to a priority.
//We need to organize the rows by the priority
arsort($results);
echo "</table>"
$mysqli->close(); //close connection
?>
This is a syntax error with your subarray declaration.
Change
$results[] = ($row => $priority);
To
$results[] = array($row => $priority);
Correction: $row is an array, that cannot be used as a key.
I think you might mean:
$results[]=array($row['taskName']=>$priority);
Or maybe:
$results[]=array($priority=>$row);
Depending on your preferred structure.
As an aside, I would replace your taskType conditional block with a lookup array as a matter of clean / more compact code which I believe is easier to maintain and read.

Get last two items of json_decode results with PHP

The following code works and pulls all the images in from the json file.
$content = file_get_contents('URL');
$json = json_decode($content, true);
foreach($json['format'] as $item) {
echo '<img src="' . $item['picture'] . '">';
}
Is there a way that I can have it only grab the last two pictures.
Yes, there is a way.
$result = array_slice($json['format'], -2);
Have a try.
Use this:
$numItems = count(foreach($json['format']);
$i = 0;
foreach($json['format'] as $item) {
if(++$i === $numItems-1) {
result1 = $json['format'][$i]
echo "first picture!";
} if(++$i === $numItems) {
result2 = $json['format'][$i]
echo "second picture!";
}
}
And result1 and result2 is your pictures
You can reverse the order of the array, run it backwards in your foreach loop, grab the first two then break.
$reversed = array_reverse($json);
$counter = 0;
foreach ($reversed['format'] as $item) {
if ($counter == 2) {
break;
}
//your echo image code
++$counter;
}
My version using array_pop:
$content = file_get_contents('URL');
$json = json_decode($content, true);
// take last element of array, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);
// take last element of array again, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);
// Beware - using `$json['format']` later means that
// you use array without two last elements

Echo statement printing more values than expected

I make call to api and in the response I receive JSON in which I access the array data like so. Problem is the JSON returns 50+ objects but I only want to echo 10 of them. In the URL that I am calling I was able to add a parameter to limit the JSON response to 10 and verified that only 10 are being returned. Problem is my echo statement still prints ALL 50+ of them.
1) How is it possible that I can echo 50+ when my JSON only returns 10?
2) Is there a For Loop that I can include below that can achieve echoing only 10?
<?php
$OfficeChartData = file_get_contents("http://api.xxxx...");
if (!empty($OfficeChartData)) {
$OfficeCharts = json_decode($OfficeChartData, true);
foreach ($OfficeCharts['value'] as $data) {
echo "<p>" . $data['Position']['Title'] . "</p>";
}
}
?>
Do something like:
<?php
$OfficeChartData = file_get_contents("http://api.xxxx...");
if (!empty($OfficeChartData)) {
$OfficeCharts = json_decode($OfficeChartData, true);
$cnt = 0;
foreach ($OfficeCharts['value'] as $data) {
if($cnt==10)break;
echo "<p>" . $data['Position']['Title'] . "</p>";
$cnt++;
}
}
?>

Counting Records in a json file?

I would like to know how to count records within records in json.
if you look here you can see an example of the text i have.
http://russellhopedesign.com/facebook/toplikedstatus/data.js
now. i want to see which record has the most "likes"
Would i have to do some sort of For Each and then count?
edit: Re-editied per ongoing conversation with the OP.
I would do a loop to start with, to loop over all the data. have a variable to store the one you want to save, too. then for each index, do a foor each loop, checking for the property and seeing if it's equal to "likes". Each time you find one that has a likes property, get the length and save it
$json = json_decode(file_get_contents('https://graph.facebook.com/100002367437090/statuses?limit=100000000&access_token=145634995501895|c19bad6810f80442a09516c5.0-100002367437090|wcIUgp977G3_nSiJTCF3mY_PMis'), true);
$data = $json['data'];
$mostLiked = null;
$saved = false;
for($i = 0; $i < count($data); $i++){
foreach($data[$i] as $key => $value){
//echo "property is => " . $key . '<br>';
if($key == "likes"){
//echo "********* a like is here";
//echo '<br><hr>';
//echo 'No. of likes => ' . count($data[$i]['likes']['data']) . '<br>';
if(!$saved){
//echo "*** nothing saved yet, save what we've just found <br>";
$mostLiked = $data[$i];
$saved = true;
}else if($saved && (count($data[$i]['likes']['data']) > count($mostLiked['likes']['data']))){
//echo "*** this one is bigger than what was saved before <br>";
$mostLiked = $data[$i];
};
};
};
};
//var_dump($mostLiked);
echo 'This post has the most likes with => ' . count($mostLiked['likes']['data']);

Categories