I’m getting this error message on my site: Notice: Undefined offset: 1 in…
I have a PHP script that should pull channel data from my database and show Twitch stream information. The problem seems to be in the section where I loop through the API response. Here’s my code:
<?php
defined('_JEXEC') or die('Access denied.');
$channelList = $params->get('channels');
$channelsArray = explode(',', $channelList);
$apiUrl = "https://api.twitch.tv/helix/streams?user_login=";
$activeStreams = array();
foreach($channelsArray as $index => $channel){
$apiUrl .= "&";
$apiUrl .= $channel;
}
unset($channel);
$response = file_get_contents($apiUrl, 0, null, null);
$data = json_decode($response, true);
// This is where the error occurs
foreach($channelsArray as $index => $channel){
$streamUrl = $data[$index]['user']['profile_url'];
$urlParts = explode('/', $streamUrl);
$username = end($urlParts);
$streamTitle = $data[$index]['title'];
$gameCategory = $data[$index]['game_name'];
$viewerCount = $data[$index]['viewer_count'];
$description = $data[$index]['description'];
displayStream($username, $viewerCount, $description, $gameCategory);
$activeStreams[] = checkStatus($username);
}
unset($channel);
unset($index);
function displayStream($streamer, $viewers, $description, $category)
{
if ($category == "Counter-Strike 2")
{
$gameIcon = "cs2.jpg";
}
else {
$gameIcon = "live.png";
}
if ($streamer != null)
{
echo ' <img src="./modules/mod_streamlist/images/'.$gameIcon.'">';
echo '<a href="https://www.twitch.tv/'.$streamer.'" target="_blank"> <strong>'.$streamer.'</strong></a>';
echo ' (' .$viewers.') - ';
echo '<strong>'.$description.'</strong> <br>';
}
}
function checkStatus($user){
if($user != null){
return $user;
}
else {
return null;
}
}
?>
<?php
foreach ($channelsArray as $i => $channel1) {
foreach($activeStreams as $j => $channel2){
if($channel1 == $channel2){
unset($channelsArray[$i]);
}
}
}
$offlineCount = count($channelsArray);
$totalStreams = count($activeStreams);
if ($offlineCount == $totalStreams){
echo '<strong><center>No streams are currently live!</center></strong>';
}
?>
What could be causing this offset error? Any suggestions would be helpful.