PHP, listing things twice - php

I'm using this script to list a few Twitch.tv streams and their status (offline or online).
If there are no online streams found, I want it to display a text saying that all are offline.
Code that checks if the added streams are online:
//get's member names from stream url's and checks for online members
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
//checks if player streams are online
function onlinecheck($online, $viewers)
{
//If the variable online is not equal to null, there is a good change this person is currently streaming
if ($online != null)
{
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
Full code:
<html>
<head>
<title>Streamlist</title>
</head>
<body>
<?php
$members = array("ncl_tv");
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($members as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
function onlinecheck($online, $viewers) {
if ($online != null) {
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
$alloffline = "All female user streams are currently offline.";
function signin($person){
if($person != null){
return $person;
}
?>
</body>
</html>
............................................................................................................................................................................

Is it because your $userGrab URL contains usernames twice? This is the URL whose contents you're retrieving:
http://api.justin.tv/api/stream/list.json?channel=painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv,painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv
Having looked at the response, it doesn't look like it's causing the problem. The strange URL is a result of you appending to the $userGrab string in the first foreach loop, after you've already added them with the implode() function call before. I think twitch.tv is rightly ignoring duplicate channels.
If all the values in $checkedOnline are null, everyone is offline. Put this at the end of your first code sample:
$personOnline = false;
foreach($checkedOnline as $person) {
if($person !== null) {
$personOnline = true;
break;
}
}
if(!$personOnline) {
echo 'No one is online';
}
else {
//there is at least someone online
}

Related

How to hide in text in php when serialized string is empty?

I am working on a website in which I want to hide text (Hello World, Point A, and Point B) when serialized string is empty. Below is my code:
<p class="font-weight-bold">Hello World</p>
<p class="font-weight-bold">Point A</p>
<?php
$serialized = '';
for ($i = 0; $i < count($data['item']->process_out); $i++) {
if(strcmp($data['item']->process_out[$i]->processs_type, "pickup") == 0)
{
$serialized .= strtolower($data['item']->process_out[$i]->processs_times);
}
}
if($serialized != '')
{
$unserialized = unserialize( $serialized );
foreach($unserialized as $key=>$value)
{
echo $key." ".$value['start']." ".$value['end']."<br/>";
}
}
?>
<p class="mt-2 font-weight-bold text-center">Point B</p>
<?php
$serialized = '';
for ($i = 0; $i < count($data['item']->process_out); $i++) {
if(strcmp($data['item']->process_out[$i]->processs_type, "location_pickup") == 0)
{
$serialized .= strtolower($data['item']->process_out[$i]->processs_times);
}
}
if($serialized != '')
{
$unserialized = unserialize( $serialized );
foreach($unserialized as $key=>$value)
{
echo $key." ".$value['start']." ".$value['end']."<br/>";
}
}
?>
Problem Statement:
Inside Hello World, I have two sections - Point A and Point B.
If both Point A and Point B are empty (meaning serialized string is empty) and there is no data to show then I don't want to show <p> text for Hello World, Point A and Point B at all.
But if either of them is present (meaning serialized string is not empty) then I want to show <p> text for Hello World and <p> text for whatever it is present (it can be Point A or Point B).
Is this possible to do? When the serialize string is empty it is displaying like this:
I don't want those texts to print when the serialized string is empty for Point A or Point B.
You should put the html output in several vars (including the 'Hello World') and do the output at the end when you did all the testing.
<?php
// pre-set/initialize some html templates/strings to be used later
$html = '';
$helloWorld_header = '<p class="font-weight-bold">Hello World</p>';
$pointA_header = '<p class="font-weight-bold">Point A</p>';
$pointA_content = '';
$pointB_header = '<p class="mt-2 font-weight-bold text-center">Point B</p>';
$pointB_content = '';
$pointA_found = $pointB_found = false; // initialize both to false
$pointA_serialized = '';
for ($i = 0; $i < count($data['item']->process_out); $i++) {
if(strcmp($data['item']->process_out[$i]->processs_type, "pickup") == 0) {
$pointA_serialized .= strtolower($data['item']->process_out[$i]->processs_times);
}
}
if($pointA_serialized != '') {
$pointA_found = true;
$unserialized = unserialize( $pointA_serialized );
foreach($unserialized as $key=>$value) {
$pointA_content .= $key." ".$value['start']." ".$value['end']."<br/>";
}
// add everything from pointA to $html
$html .= $pointA_header . $pointA_content;
}
$pointB_serialized = '';
for ($i = 0; $i < count($data['item']->process_out); $i++) {
if(strcmp($data['item']->process_out[$i]->processs_type, "location_pickup") == 0) {
$pointB_serialized .= strtolower($data['item']->process_out[$i]->processs_times);
}
}
if($pointB_serialized != '') {
$pointB_found = true;
$unserialized = unserialize( $pointB_serialized );
foreach($unserialized as $key=>$value) {
$pointB_content . $key." ".$value['start']." ".$value['end']."<br/>";
}
// add everything from pointB to $html
$html .= $pointB_header . $pointB_content;
}
// if pointA or pointB is set/found...
if($pointA_found || $pointB_found) {
// ... add the main header before the rest
$html = $helloWorld_header + $html;
}
// do the actual output
echo $html
?>
This is just a quick fix of what you've got. There would be more elegant ways to do that. I'd put pointA and pointB in a shared function, as you mostly do twice the same thing.

Display values without array (print_r)

I have a function that displays the actors photos from TMDB to my website is there a way that I can make it print without an array, it prints only with print_r I want to know if I can print it like echo or print.
This is the code:
public function getCasts($movieID)
{
if (empty($movieID)) return;
function cmpcast($a, $b)
{
return ($a["order"]>$b["order"]);
}
$temp = $this->_call("movie/" . $movieID . "/casts");
$casts = $temp['cast'];
$temp = array();
if (count($casts) > 0)
{
usort($casts, "cmpcast");
foreach ($casts as &$actor) {
if (!empty($actor['profile_path'])) {
for ($i=6; $i<count($temp['id']); $i++)
if ($temp['name'][$i] == $actor['name']) $temp['char'][$i] .= " / ".str_replace('(voice)', '(hang)', $actor['character']);
if (!in_array($actor['name'], (array) $temp['name'])) {
$temp['pic'][] = "<div style='margin-top:15px;' align='center'><div style='width:140px;margin-right:8px;display:inline-block;vertical-align:top;'><img style='width:130px;height:130px;border-radius:50%;' src='".$this->getImageURL().$actor['profile_path']."'><br />".$actor['name']."<br />".$actor['character']."</div></div>";
}
}
}
}
return $temp;
}
You could use some kind of loop. Use a for loop if you want to limit the number of item you echo.
For example :
$casts = getCasts(1);
for ($i = 0; $i < 5; $i++) {
if (isset($casts['pic'][$i])) {
echo $casts['pic'][$i];
}
}
Hope it helps.

Weird behaviour when searching for char in array string elements

<?php
ini_set('error_reporting', '-1');
ini_set('display_errors', '1');
ini_set('apc.enabled', '0');
gc_enable();
$array = array("php", "php_php", "php_php", "php_php", "php");
$arraysize = count($array);
$style = " style='border: 1px solid black;'";
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
foreach ($array as $key)
{
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
if (strstr($key, "_") !== false)
{
$strstr[] = "found";
$explodedstring1[] = explode("_", $key);
}
else
{
$strstr[] = "not found";
$explodedstring1[] = "not found";
}
if (strpos($key, "_") !== false)
{
$strpos[] = "found";
$explodedstring2[] = explode("_", $key);
}
else
{
$strpos[] = "not found";
$explodedstring2[] = "not found";
}
if (preg_match("/[^_+$]/", $key))
{
$preg_match[] = "found";
$explodedstring3[] = explode("_", $key);
}
else
{
$preg_match[] = "not found";
$explodedstring3[] = "not found";
}
$keysize = strlen($key);
for ($i = 0; $i < $keysize; $i++)
{
if (strcmp($key[$i], "_") === 0) { $strcmpcharcount++; }
}
for ($j = 0; $j < $keysize; $j++)
{
if ($key[$j] === "_") { $equalcmpcharcount++; }
}
if ($strcmpcharcount > 0)
{
$strcmp[] = "found";
$explodedstring4[] = explode("_", $key);
}
else
{
$strcmp[] = "not found";
$explodedstring4[] = "not found";
}
if ($equalcmpcharcount > 0)
{
$equalcmp[] = "found";
$explodedstring5[] = explode("_", $key);
}
else
{
$equalcmp[] = "not found";
$explodedstring5[] = "not found";
}
}
echo "<table$style>
<th$style>
<tr>
<td$style>strstr()</td>
<td$style>strpos()</td>
<td$style>preg_match()</td>
<td$style>strcmp()</td>
<td$style>'==='</td>
</tr>
</th>";
for($k = 0; $k < $arraysize; $k++)
{
echo "<tr>
<td$style>$strstr[$k]</td>
<td$style>$strpos[$k]</td>
<td$style>$preg_match[$k]</td>
<td$style>$strcmp[$k]</td>
<td$style>$equalcmp[$k]</td>
</tr>";
}
echo "</table>";
exit();
?>
The problem is with first two functions - they randomly fails to find the underscore char. In fact I called more than 50 times the script to got proper results. Added and preg_match() test but just to know I'm not sure if it has valid regex.
You're adding new elements to $strstr, $strpos tables and so on and in the end you do for... and printing from these tables where $k keys don't necessarily have to exists.
Check var_dump or print_r on these tables and you will see that in fact they got elements, but their indexes aren't matched with $array indexes (and i guess that's what you want to achieve).
You can change foreach ($array as $key) to foreach ($array as $index => $key) and all occurences like $strstr[] = "found"; to $strstr[$index] = "found"; (also for other recognision methods) and then run the script again to see results.
In last block (for($k = 0; $k < $arraysize; $k++)...) you should either validate if $strstr[$k] (and other arrays) exists before printing it, or print these arrays separately by foreach.
You can also make one table for results and make it multidimensional with function names as keys in the first level and put results in there.

show an array() into table

My primary task was, to validate that the backlinks of my website is there or not which is validated through a some.txt file. I have done it but now the problem is, I want the urls in table format.
My script is this
$needle = $_GET['utext'];
$file = $_GET['ufile'];
$source = file_get_contents($file);
$new = explode("\n",$source);
foreach ($new as $check)
{
$a = file_get_contents(trim($check));
if (strpos($a,$needle))
{
$found[] = $check;
}
else
{
$notfound[] = $check;
}
}
echo "Matches that were found: \n ".implode("\n",$found)."\n";
echo "Matches that were not found \n". implode("\n",$notfound);

Recursive function - tree view - <ul> <li> ... (stuck)

It seems that I'm stuck with my recursive function.
I have a problem with closing the unnamed list (</ul>) and the list-items (</li>)
The thing what i get is
-aaa
-bbb
-b11
-b22
-b33
-ccc
-c11
-c22
-c33
-ddd
-d11
-d22
-d33
-eee
-fff
And the thing what i want is:
-aaa
-bbb
-b11
-b22
-b2a
-b2c
-b2b
-b33
-ccc
-c11
-c22
-c33
-c2a
-c2c
-c2c1
-c2c2
-c2b
-ddd
-d11
-d22
-d33
-eee
-fff
This is the code that i'm using
$html .= '<ul>';
$i = 0;
foreach ($result as $item)
{
$html .= "<li>$item->id";
$html .= getSubjects($item->id, NULL, "",$i); <--- start
$html .= "</li>";
}
$html .= '</ul>';
And the function
function getSubjects($chapter_id = NULL, $subject_id = NULL, $string = '', $i = 0 ) {
$i++;
// getting the information out of the database
// Depending of his parent was a chapter or a subject
$query = db_select('course_subject', 'su');
//JOIN node with users
$query->join('course_general_info', 'g', 'su.general_info_id = g.id');
// If his parent was a chapter - get all the values where chapter id = ...
if ($chapter_id != NULL) {
$query
->fields('g', array('short_title', 'general_id'))
->fields('su', array('id'))
->condition('su.chapter_id', $chapter_id, '=');
$result = $query->execute();
}
// if the parent is a subject -
// get value all the values where subject id = ...
else {
$query
->fields('g', array('short_title', 'general_id'))
->fields('su', array('id'))
->condition('su.subject_id', $subject_id, '=');
$result = $query->execute();
}
// Because count doesn't work (drupal)
$int = 0;
foreach ($result as $t) {
$int++;
}
// if there no values in result - than return the string
if ($int == 0) {
return $string;
}
else {
// Creating a new <ul>
$string .= "<ul>";
foreach ($result as $item) {
// change the id's
$subject_id = $item->id;
$chapter_id = NULL;
// and set the string --> with the function to his own function
$string .= "<li>$item->short_title - id - $item->id ";
getSubjects(NULL, $subject_id, $string, $i);
$string .="</li>";
}
$string .= "</ul>";
}
// I thougt that this return wasn't necessary
return $string;
}
Does someone have more experience with this kind of things?
All help is welcome.
I am not sure what you are trying to do but here is some code you can test and see if it helps to solve your problem:
This part is just for testing, it makes three dimensional array for testing:
for ($x = 0; $x < 2; $x++) {
$result["c$x"] = "ROOT-{$x}";
for ($y = 0; $y < 3; $y++) {
$result[$x]["c$y"] = "SECOND-{$x}-{$y}";
$rnd_count1 = rand(0,3);
for ($z = 0; $z < $rnd_count1; $z++) {
$result[$x][$y]["c$z"] = "RND-{$x}-{$y}-{$z}";
$rnd_count2 = rand(0,4);
for ($c = 0; $c < $rnd_count2; $c++) {
$result[$x][$y][$z][$c] = "LAST-{$x}-{$y}-{$z}-{$c}";
}
}
}
}
// $result is now four dimensional array with some values
// Last two levels gets random count starting from 0 items.
UPDATE:
Added some randomness and fourth level to test array.
And here is function which sorts array to unordered list:
function recursive(array $array, $list_open = false){
foreach ($array as $item) {
if (is_array($item)) {
$html .= "<ul>\n";
$html .= recursive($item, true);
$html .= "</ul>\n";
$list_open = false;
} else {
if (!$list_open) {
$html .= "<ul>\n";
$list_open = true;
}
$html .= "\t<li>$item</li>\n";
}
}
if ($list_open) $html .= "</ul>\n";
return $html;
}
// Then test run, output results to page:
echo recursive($result);
UPDATE:
Now it should open and close <ul> tags properly.

Categories