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

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.

Related

How can I remove random amount of dots and get the last number?

I'm trying to strip all the dots and then get the number, and NAME[X] as an output.
My output is:
NAME..................................................................................................3
NAME2...................................................................................................24
NAME3...............................................................................................................................................5
NAME4.......................347
NAME5............................................................................................7
NAME6......................................................................9
I've tried something like this so far:
function introExcerpt($id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = 'my string';
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
// if (isset($lines[$i]) && substr(trim($lines[$i]), -1) !== '.') {
$intro.= $lines[$i].'<br />';
//}
}
$intro .= '</div></ul>';
return $intro;
}
Not sure exactly what your output should look like, but you may try just running preg_replace directly on the variable containing all lines:
$lines = preg_replace("/(NAME\d+)\.+(\d+)/", "$1[$2]", $lines);
This would generate the following output based on your sample input:
NAME[3]
NAME2[24]
NAME3[5]
NAME4[347]
NAME5[7]
NAME6[9]
You can use the following function:
function introExcerpt($str, $id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = $str;
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
$intro .= '<li>';
$tmpLineArray = explode('.', $lines[$i]);
array_filter($tmpLineArray, function ($value) {
return !is_null($value) && $value != '';
});
foreach ($tmpLineArray as $value) {
$intro .= $value . ' ';
}
$intro .= '</li>';
}
$intro .= '</ul></div>';
return $intro;
}
It is splitting the entire row into array using dot as separator and filters out the empty elements.

PHP look-and-say sequence

I'm trying to code Conway look-and-say sequence in PHP.
Here is my code:
function look_and_say ($number) {
$arr = str_split($number . " ");
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
return $res;
}
As I run the function, look_and_say(9900) I am getting value I expected: 2920.
My question is for assigning $arr to be $arr = str_split($number) rather than $arr = str_split($number . " "), the result omits the very last element of the $arr and return 29.
Is it normal to add empty space at the end of the $arr foreach to examine the last element or is there any better way to practice this code - besides regex way.
There are 2 methods I was able to come up with.
1 is to add concatenate at the result after the loop too.
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
$res .= $count . $target;
return $res;
}
And the 2nd one is to add another if clause inside the loop and determine the last iteration:
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
$i=0;
$total = count($arr);
foreach($arr as $num){
if($i == ($total-1))
{
$count++;
$res .= $count . $target;
}
elseif($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
$i++;
}
return $res;
}
I want to suggest you other way using two nested while loops:
<?php
function lookAndSay($number) {
$digits = str_split($number);
$result = '';
$i = 0;
while ($i < count($digits)) {
$lastDigit = $digits[$i];
$count = 0;
while ($i < count($digits) && $lastDigit === $digits[$i]) {
$i++;
$count++;
}
$result .= $count . $lastDigit;
}
return $result;
}

Split array into two ul columns

I am grabbing a list of occupations for an API and putting them into an array of titles like this:
$titles = array();
$arr = $doc->getElementsByTagName("h4");
foreach($arr as $item) {
$titles[] = $item->nodeValue;
}
$content = occupations_html($titles);
return $content;
I then spit those titles out into an unordered list/list items like this:
function occupations_html($titles){
$content = '<ul><li>';
$content .= implode('</li><li>', $titles);
$content .= '</li></ul>';
return $content;
}
This works great for creating one unordered list, but I am having trouble spitting this dynamic list out into two even ul's.
Try this you can do the ul splitting your self:
$i=0;
foreach($array as $value) {
if ($i++ % 3 == 0) {
$column1[] = $value;
}
if ($i++ % 3 == 1) { // check mod==1
$column2[] = $value;
}
if ($i++ % 3 == 2) { // check mod==2
$column3[] = $value;
}
}
You can use a function like so
function array_column_chunk($data, $columns = 2, $preserve_keys = false){
return array_chunk($data, ceil(count($data) / $columns), $preserve_keys);
}
Which will chunk your array into the number of columns you would like instead of the length of the chunks you want.

Adding PHP code in extension after every nth list element in TYPO3

I'm using old fashion way (kickstarter) to build extension in TYPO3. I would like to ad some PHP code after third element of list, but I really don't know how to do this.
My code looks like that:
protected function makeList($res) {
$items = array();
// Make list table rows
while (($this->internal['currentRow'] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
$items[] = $this->makeListItem();
}
$out = '<div' . $this->pi_classParam('listrow') . '>list items</div>';
return $out;
}
And:
protected function makeListItem() {
$out = 'list item details';
return $out;
}
If I understood correctly, you would need something like this:
protected function makeList($res) {
$items = array();
// Make list table rows
$i = 0;
$out = '<div' . $this->pi_classParam('listrow') . '>';
while (($this->internal['currentRow'] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
$out .= $this->makeListItem();
$i++;
if ($i == 3) {
$out .= '<img src="whateverjpg">';
$i = 0; // if you want to do it every 3 images
}
}
$out .= '</div>';
return $out;
}

PHP, listing things twice

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
}

Categories