Ron Melkhior Ron Melkhior - 4 months ago 15
PHP Question

Padding when sorting categories fails and mis-sorts

I'm trying to code a channel viewer for my Teamspeak 3 server (which has parent and child channels/categories, and child channels to the child channels and so on), but when trying to style it and add padding depends on where it is, it fails and turns out like this:

how it looks

While it's supposed to look like this: (obviously not as styled, but you get my point)

how it's supposed to look

Here's my code:

private $_allChannels = array();
private $_allClients = array();

private function showChannels($parentID, $padding)
{
$response = '';

foreach ($this->_allChannels as $channel) {
$channelParent = $channel['pid'];
$channelID = $channel['cid'];
$channelName = $channel['name'];

if ($channelParent == $parentID) {
$response .= '<span style="margin-left: ' . $padding*2 . 'em;">' . $channelName . '</span><br>';
$response .= $this->showChannels($channelID, $padding++);
}
}

return $response;
}

public function index()
{
$teamspeakServer = TeamSpeak3::factory("serverquery://user:pass@IP:QueryPort/?server_port=ServerPort");

$allClients = $teamspeakServer->clientList(['client_type' => 0]);
$allChannels = $teamspeakServer->channelList();

foreach ($allChannels as $channel) {
array_push($this->_allChannels, array('pid' => $channel['pid'], 'name' => $channel['channel_name'], 'cid' => $channel['cid']));
}

echo $this->showChannels(0, 0);
}


I'll appreciate any help, thanks!

Answer

Reading over the code, you are just constantly adding to the padding. $padding++ will increment the value and save it back into $padding. On next loop you keep adding to it again. If I had to guess, you would want that to be just $padding+1 which would add 1, but not overwrite $padding with the new $padding+1 value.