Array does not remove all elements - php

$channels = array('imaqtpies','imsoff','zzero71tv', 'kaptenen', 'onlySinged', 'nightblue3') ;
$nr = 0;
$callAPI = implode(",",$channels);
$online = 'online.png';
$offline = 'offline.png';
$json = file_get_contents('https://api.twitch.tv/kraken/streams?channel=' . $callAPI);
$dataArray = json_decode($json, true);
foreach($dataArray['streams'] as $mydata){
echo $mydata['channel']['name'] . ' is online';
echo '<br /><hr />';
unset($channels[$nr]);
$nr++;
}
$newChannels = array_values($channels);;
foreach($newChannels as $channel) {
echo $channel . ' is offline';
echo '<br /><hr />';
}
Not all the names are echoed in the "offline" part and some names are being echoed twice (both in online and offline).

$mydata['channel']['name'] and $nr are not aligned. You're unsetting the first x channels but I don't see why twitch should return them in the order you've defined your channels.
You will want something like:
$online_channels = array();
foreach($dataArray['streams'] as $stream){
$online_channels[] = $stream["channel"]["name"];
}
$offline_channels = array_diff($channels, $online_channels);
Then print $online_channels and $offline_channels.

Related

PHP loop outputting duplicates

public function select(){
$rows = [];
$connection = $this->connect();
$result = $connection->query("SELECT username FROM users");
while ($row = $result->fetch_assoc()){
$rows[] = $row;
}
$userlist = 0;
foreach($rows as $username){
$userlist .= $username['username'];
}
$get_rankings = [1,2,3,4];
$get_image_path = "images/";
$total = 0;
for ($x = 0; $x < count($get_rankings); $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $userlist . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}
echo $path;
}
I'm trying to output a simple ranking but using the number index as images to display them.
In the past i've tried to do something similar but couldn't figure out how to match player it with images on the side.
The output im getting is this:
It's outputting each entry 4 times(I get why, its in a loop) but I can't figure out the correct solution to write it outside of a loop or properly
The desired output is:
My DataBase reads as:
[id][username][password]
If there is an easier solution, i'm all ears. I don't know how to approach this.
There's no need for $userlist. Output the username from $rows[$x].
$path = "";
$max = min(count($rows), count($get_rankings));
for ($x = 0; $x < $max; $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $rows[$x]['username'] . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}

i want add multiple product using php session

I want to print both
<?php
//in file A
$_SESSION['cart']['prices'] = array('1000');
$_SESSION['cart']['services'] = array('game');
//In File B
$_SESSION['cart']['prices'] = array('2000');
$_SESSION['cart']['services'] = array('game2');
//in file C
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}
?>
Better use this :
$_SESSION['cart']['prices'][] = array('1000');
$_SESSION['cart']['services'][] = array('game');
//In File B
$_SESSION['cart']['prices'][] = array('2000');
$_SESSION['cart']['services'][] = array('game2');
According to the current data foreach loop will execute two times. It will print Array as $service is array array('1000') and array('2000') same as for $_SESSION['cart']['prices'][$key]
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}
Try this :
$array1 = array('1000','2000');
$array2 = array('game1','game2');
foreach($array1 as $index=>$key)
{
$_SESSION['cart']['prices'][] = $key;
$_SESSION['cart']['services'][] = $array2[$index];
}
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}

foreach loop does not work with include

Would someone of you know why I'm not able to use a (long)piece of code within a foreach loop?
The code in the foreach loop is only executed once.
This code at topictweets.php works fine on its own but I want to repeat it for each forum.
The foreach loop works fine without the include. I also tried to have the code from topic tweets.php plainly in the foreach loop, this didn't work either of course.
The code it includes is used to get topics of a forum from the database and find related tweets, and save those in the database.
Is there some other way to do this?
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
include 'topictweets.php';
/////////
////////
}
online version: http://oudhollandsedrop.nl/webendata/FeedForum/fetchtweets.php
bunch of code in topic tweets.php
<?php
//?/ VVVV ---- SELECT TOPICS FOR CURRENT FORUM ----- VVVV ////
echo $fID;
$sql = "SELECT Topics_TopicID
FROM Topics_crosstable
WHERE Forums_ForumID = '$fID'";
$result = mysql_query($sql);
if (!$result) {
//echo 'The topiclist could not be displayed, please try again later.';
} else {
if (mysql_num_rows($result) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($result)) {
//display post data
// echo $row['Topics_TopicID'];
// echo': ';
$topic = "SELECT Name
FROM Topics
WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID']);
$topicname = mysql_query($topic);
if (!$topicname) {
// echo 'The topic could not be displayed, please try again later.';
} else {
if (mysql_num_rows($topicname) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($topicname)) {
//display post data
// echo $row['Name'];
// echo'<br>';
$topiclist[] = $row['Name'];
}
}
}
}
}
}
foreach ($topiclist as $key => $value) {
$terms .= "" . $value . ",";
}
//echo'<p>';
//echo rtrim($terms, ",");
//echo'<p>';
//echo'<p>';
//echo $terms;
//$terms="vintage";
//Twitter account information
$username = "Username";
$password = "Password";
while (true) {
//$terms="vintage";
//echo "search terms: " . substr_replace($terms, "", -1) . "\n";
$url = "https://stream.twitter.com/1/statuses/filter.json";
$cred = sprintf('Authorization: Basic %s', base64_encode("$username:$password"));
$param = "track=" . urlencode(substr_replace($terms, "", -1));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => $cred,
'content' => $param,
'Content-type' => 'application/x-www-form-urlencoded'),
'ssl' => array('verify_peer' => false)
);
$ctx = stream_context_create($opts);
$handle = fopen($url, 'r', false, $ctx);
//var_dump($handle);
$content = "";
$flag = true;
while ($flag) {
$buffer = fread($handle, 100);
//$buffer = stream_get_line($handle, 1024, "\n");
$a = explode("\n", $buffer, 2);
$content = $content . $a[0];
#var_dump($a);
if (count($a) > 1) {
#echo $content;
#echo "\n";
$r = json_decode($content, true);
#var_dump($r);
// echo '<p>';
// echo "text: " . $r["text"];
// echo '<br>';
// echo "\nrceated_at: " . $r["created_at"];
// echo '<br>';
// echo "\nuser screen name: " . $r["user"]["screen_name"];
// echo '<br>';
// echo "\nuser id: " . $r["user"]["id"];
// echo '<br>';
// echo "\nid : " . $r["id"];
// echo '<br>';
// echo "\nin_reply_to_status_id: " . $r["in_reply_to_status_id"];
// echo '<p>';
// echo "\n\n";
$created_at = $r["created_at"];
$created_at = strtotime($created_at);
$mysqldate = date('Y-m-d H:i:s', $created_at);
//
// echo'<p>';
foreach ($topiclist as $key => $value) {
// echo'getshere!';
//$whichterm = $r["text"];
$whichterm = '"' . $r["text"] . '"';
//echo $whichterm;
if (stripos($whichterm, $value) !== false) {
// echo 'true:' . $value . '';
//find topicid
$whattopic = "SELECT TopicID
FROM Topics
WHERE Name = '$value'";
//var_dump($whattopic);
$tID = mysql_query($whattopic);
//var_dump($tID);
if (!$tID) {
// echo 'topic id not found.';
} else {
if (mysql_num_rows($tID) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($rec = mysql_fetch_assoc($tID)) {
$inserttweets = "INSERT INTO
Tweets(Topics_TopicID, AddDate, Tweetcontent)
VALUES('" . mysql_real_escape_string($rec['TopicID']) . "',
'" . mysql_real_escape_string($mysqldate) . "',
'" . mysql_real_escape_string($r["text"]) . "')";
//WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID'])
}
}
$addtweet = mysql_query($inserttweets);
if (!$addtweet) {
//something went wrong, display the error
//echo 'Something went wrong while adding tweet.';
//echo mysql_error(); //debugging purposes, uncomment when needed
} else {
echo 'Succesfully added tweet';
}
}
}
}
die();
$content = $a[1];
}
}
fclose($handle);
}
?>
"Pasting" a bunch of code inside a loop isn't a great practice. In fact, what you're looking for is a function or the use of a defined class. So, if you can, define a function in your topictweets.php that will contain your code and use it in your loop:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
processYourForums($fID);
/////////
////////
}
try include_once()
however, why not have a loop within topictweets.php?
you can do the query, etc.. in this page, but then loop through it in the include
This should work fine:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
}
You only need to include once.

php report is very slow and crashes in firefox

I have a report that runs and returns 366 records, each containing a thumbnail that is 104 x 80 px. The issue is that the report runs very slowley even though I increased the memory size.
ini_set('memory_limit', '128M');
ini_set('max_execution_time','600');
After writing the SQL query I generate the table items here
generate_table_items($query_all_items);
This then runs through and checks for the image in the columns
function generate_table_items($query){
$columns = array();
$resultset = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$columncount = 0;
$rowcost = 0;
$rowsale = 0;
while ($row = mssql_fetch_assoc($query)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th scope="col" >'.implode('</th><th scope="col" >',get_column_name($columns)).'</th></tr>';
$columncount = sizeof(array_keys($row));
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>',report_image_check($row)).'</td></tr>';
if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$colspan = (count($columns)-2);
echo "<tr><th scope='row'>Documents</th><td colspan='$colspan' >";
$PKID = $row['ID'];
if($row['SumOfTotalCost'] || $row['SumOfSalePrice']){
$rowcost += $row['SumOfTotalCost'];
$rowsale += $row['SumOfSalePrice'];
$get_total = true;
}
$query_docs = mssql_query("select documents.* from dbo.documents where documents.Antiquities_id = $PKID") or die ('get docs query failed ' . mssql_get_last_message());
while($row_docs = mssql_fetch_assoc($query_docs)){
$document = "../documents/" . $row_docs['document'];
echo "<a href='$document' title='opens in a new window' target='_blank' >" . $row_docs['document'] . "</a> | ";
} // End while (list docs)
mssql_free_result($query_docs);
echo "</td></tr>";
myflush();
} // End if all items and all items by value report
} // End While
echo '<tr>';
for($i=0;$i < $columncount-4;$i++){
echo '<td> </td>';
}
echo '<td>Total Cost '. $rowcost.'</td>';
echo '<td>Total Sale '. $rowsale.'</td>';
echo '<td>Total Calculated Difference '. ($rowsale-$rowcost).'</td></tr>';
} // End function
function get_column_name($columns){
$newcol = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$thecount = 0;
foreach($columns as $col) {
if($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
// Don't list the PK
} else {
$newcol[] = '<img id="'.$col.'" src="../images/icons/arrow_down.png" alt="click to sort by" onclick="sortby(\''.$col.'\');" />' . $col;
}
$thecount++;
}
/*if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$newcol[] = "documents";
}*/
return $newcol;
}
function report_image_check($row){
global $base_url, $uploaded_images_folder;
$newrow = array();
$imageext = array();
$imageext[0] = ".jpg";
$imageext[1] = ".png";
$imageext[2] = ".gif";
$imageext[3] = ".tiff";
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$PKID = 0;
$thecount = 0;
foreach($row as $rn) {
if(in_array(strtolower(substr($rn,-4)),$imageext)){
$small_img_ext = substr($rn,-4);
$small_img = substr($rn,0,strripos($rn,"."));
$small_img = $small_img . '_140_105' . $small_img_ext;
$newrow[] = '<a href="' . $base_url . $uploaded_images_folder . '/' . $small_img . '" title="click to zoom on image" target="_blank" ><img src="' . $base_url . $uploaded_images_folder . '/' . $rn . '" alt="" width="50px" height="50px" /></a>';
} elseif($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$PKID = $rn;
} elseif($thecount == 2 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='../index.php?template=10&PKID=$PKID' target='_blank' >$PKID (click to view)</a>";
} else {
$newrow[] = $rn;
}
$thecount++;
myflush();
}
/*if (in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='#&PKID=$PKID' target='_blank' >Documents (click to view)</a>";
}*/
return $newrow;
} // End function
//// Flushing function
function myflush(){
ob_implicit_flush();
ignore_user_abort();
}
Can anyone see an issue with this code or see why it would take so long or why it crashes firefox? Would printing to pdf function work better?
It'll take a long time because you're nesting SQL queries... executing a second SQL query for every result that has been returned by the first query.... Doing a single query with a JOIN should help performance significantly.
Printing to PDF would almost certainly be slower: you'd eithe rneed a lot of code to position everything correctly in the report yourself, or to use one of the libraries that can take HTML and render it to a PDF (as you're already generating HTML anyway at the moment, this would be additional processing)

Web service Array problem

I have this web service http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Social/Login?Token=210029242357724|fd4eef8a839f24db2a9fedcd.1-100001001235070|Nro7dAY411DJRn7E8zB6MOXHjq8
And I'm having problems catching some values like:
clubId, clubName, clubLogo, relationType, and dateAdded.
I just don't know how to handle the array.
My code:
<?php
function getUserInfo() {
$json = file_get_contents('http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Social/Login?Token=210029242357724|fd4eef8a839f24db2a9fedcd.1-100001001235070|Nro7dAY411DJRn7E8zB6MOXHjq8');
$data = json_decode($json, TRUE);
$v= $data['data'];
$_SESSION['userinfid'][] = $v['id'];
$_SESSION['userinfnickname'][] = $v['nickname'];
$_SESSION['userinfvisibility'][] = $v['visibility'];
$_SESSION['userinffirstname'][] = $v['first_name'];
$_SESSION['userinflastname'][] = $v['last_name'];
$_SESSION['userinfgender'][] = $v['gender'];
$_SESSION['userinfdialect'][] = $v['dialect'];
$_SESSION['userinfstatus'][] = $v['status'];
$_SESSION['userinfadmissiondate'][] = $v['admission_date'];
$_SESSION['userinflastaccess'][] = $v['last_access'];
$_SESSION['userinfusername'][] = $v['username'];
$_SESSION['userinfpoints'][] = $v['points'];
$_SESSION['userinfranking'][] = $v['ranking'];
$_SESSION['userinfsessionID'][] = $v['sessionID'];
$_SESSION['userinfpublicProfile'][] = $v['publicProfile'];
$_SESSION['userinfemail'][] = $v['email'];
$_SESSION['userinfmobile'][] = $v['mobile'];
$_SESSION['userinfimageURL'][] = $v['imageURL'];
$_SESSION['userinfclubURL'][] = $v['clubURL'];
$_SESSION['userinfcontact'][] = $v['contacts']['contact'];
$_SESSION['userinfcontactType'][] = $v['contacts']['contactType'];
$_SESSION['userinfisdefault'][] = $v['contacts']['is_default'];
$_SESSION['userinfclubId'][] = $v['clubs']['clubId'];
$_SESSION['userinfclubName'][] = $v['clubs']['clubName'];
$_SESSION['userinfclubLogo'][] = $v['clubs']['clubLogo'];
$_SESSION['userinfrelationType'][] = $v['clubs']['relationType'];
$_SESSION['userinfdateAdded'][] = $v['clubs']['dateAdded'];
}
getUserInfo();
echo 'IDClube: ' . $_SESSION['userinfclubId'][0] . '<br />';
echo 'NomeClube: ' . $_SESSION['userinfclubName'][0] . '<br />';
echo 'LogoClube: ' . $_SESSION['userinfclubLogo'][0] . '<br />';
echo 'RelationType: ' . $_SESSION['userinfrelationType'][0] . '<br />';
echo 'DataAdicionado: ' . $_SESSION['userinfdateAdded'][0] . '<br />';
?>
And if there is only one value for each key of session then
<?php
function getUserInfo() {
$json = file_get_contents('http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Social/Login?Token=210029242357724|fd4eef8a839f24db2a9fedcd.1-100001001235070|Nro7dAY411DJRn7E8zB6MOXHjq8');
$data = json_decode($json, TRUE);
$v= $data['data'];
foreach($v as $key => $value)
{
$_SESSION['userinf'.$key] = $value;
}
}
getUserInfo();
echo 'IDClube: ' . $_SESSION['userinfclubs']['clubId'] . '<br />';
echo 'NomeClube: ' . $_SESSION['userinfclubs']['clubName'] . '<br />';
echo 'LogoClube: ' . $_SESSION['userinfclubs']['clubLogo'] . '<br />';
echo 'RelationType: ' . $_SESSION['userinfclubs']['relationType'] . '<br />';
echo 'DataAdicionado: ' . $_SESSION['userinfclubs']['dateAdded'] . '<br />';
Be careful,there's more than one club in clubs, so you'll need to do something like this :
foreach ($v['clubs'] as $value) {
$_SESSION['userinfclubId'][] = $value['clubId'];
$_SESSION['userinfclubName'][] = $value['clubName'];
$_SESSION['userinfclubLogo'][] = $value['clubLogo'];
$_SESSION['userinfrelationType'][] = $value['relationType'];
$_SESSION['userinfdateAdded'][] = $value['dateAdded'];
}

Categories