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

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;
}

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 - echo the opening and closing of tags from array

Here I have an array and there is content situated inside it, their is either, one object, two, or more - depending on the tags required; the first element nested in the multidimensional array would be the textual output, unless it is an array, then the first element inside the array would be the text.
However, the other content in the array is in reference to the HTML tag they correspond to, such as:
[1] => Array
(
[0] => bo <====== Text to output
[1] => bold <====== tag to be within
)
However, in the module of simplicity, I would prefer for the content not to constantly repeat such responses, like:
This is a test <b>bo</b><i><b>ld</b></i><i>,</i> <u><i>u</i></u><u>nderline</u> ...
Instead the output should be:
This is a test<b>bo<i>ld</i></b><i>, <u>u</u></i><u>nderline</u> ...
This is the PHP code I have for it so far...
$use = array();
$base = "";
foreach ($build as $part => $data) {
// print_r($use);
if(!is_array($data)){
$base .= $data;
} else {
$text = array_shift($data);
if(!is_array($data[0])){
$data = array($data[0]);
} else {
$data = $data[0];
}
$removed = array_diff($use,$data);
foreach (($data) as $tag) {
if (in_array($tag, array_diff($use,$data))) {
$base .= "<\/" . $tag . ">";
} elseif(!in_array($tag, $use)){
$base .= "<" . $tag . ">";
array_push($use, $tag);
}
}
$use = $data;
$base .= $text;
}
}
print_r($base);
And here is the array if required (in JSON format!):
["This is a test\nIncluding ",["bo","bold"],["ld",["italic","bold"]],[", ","italic"],["u",["underline","italic"]],["nderlined","underline"],", ",["strike-through","strike"],", and ",["italic","italic"],"\ntext:\n\n",["numbered lists",["underline","strike","italic","bold"]],["\n",[]],"as well as",["\n",[]],["non ordered lists","http:\/\/test.com"],["\n",[]],"it works very well",["\n",[]],["try it","http:\/\/google.com"],"\n",["http:\/\/google.com",["bold","http:\/\/google.com"]],"\n\n",["wow","bold"],"\n",["lol","bold"]]
Any help would be much appreciated... thanks!
I'm honestly not sure if this is exactly what you're looking for. It would be great to have a full desired output... but I believe this is as close as it gets. It took me 3 hours so it better be it. It's a great question, very hard to accomplish.
I did print_r(htmlentities($base)), but you can simply do print_r($base) to see the formatted result. I did that because it was easier to check with the output you provided in the question.
Also, I modified your JSON because some tags specified there are non-existent. For example, I changed underline for u, italic for i, bold for b. Alternatives are em, strong... anyway, that's just a side-note.
<?php
$build = json_decode('["This is a test\nIncluding ",["bo","b"],["ld",["i","b"]],[", ","i"],["u",["u","i"]],["nderlined","u"],", ",["strike-through","strike"],", and ",["italic","i"],"\ntext:\n\n",["numbered lists",["u","strike","i","b"]],["\n",[]],"as well as",["\n",[]],["non ordered lists","http:\/\/test.com"],["\n",[]],"it works very well",["\n",[]],["try it","http:\/\/google.com"],"\n",["http:\/\/google.com",["b","http:\/\/google.com"]],"\n\n",["wow","b"],"\n",["lol","b"]]', true);
$used = [];
$base = '';
foreach($build as $data){
if(is_array($data)){
$text = array_shift($data);
$tags = $data[0];
if(!is_array($data[0])){
$tags = [$data[0]];
}
$elements = '';
$tagsToClose = array_diff($used, $tags);
$changes = true;
$i = 0;
foreach($tagsToClose as $tag){
while($changes){
$changes = false;
if($lastOpened != $tag){
$changes = true;
$elements .= '</'.$lastOpened.'>';
unset($used[$i++]);
$lastOpened = $used[$i];
}
}
$elements .= '</'.$tag.'>';
$key = array_search($tag, $used);
unset($used[$key]);
}
foreach($tags as $tag){
if(!in_array($tag, $used)){
$elements .= '<'.$tag.'>';
array_unshift($used, $tag);
$lastOpened = $tag;
}
}
$elements .= $text;
$data = $elements;
}
$base .= $data;
}
unset($used);
$base .= '</'.$lastOpened.'>';
print_r(htmlentities($base));
?>
EDIT
And here's the result I got, just in case you run into some trouble testing or to check with your results or whatever:
This is a test Including <b>bo<i>ld</i></b><i>, <u>u</u></i><u>nderlined, </u><strike>strike-through, and </strike><i>italic text: <u><strike><b>numbered lists</b></strike></u></i> as well as <http://test.com>non ordered lists</http://test.com> it works very well <http://google.com>try it <b>http://google.com </b></http://google.com><b>wow lol</b>
After many hours, this was my solution that I ended up with:
$build = json_decode('["This is a test Including\u00a0",["bo","bold"],["ld",["italic","bold"]],[",\u00a0","italic"],["u",["underline","italic"]],["nderlined,\u00a0","underline"],"strike-through, and\u00a0",["italic text:\u00a0","italic"],"it works very well\u00a0try it\u00a0",["http:\/\/google.com",["bold","http:\/\/google.com"]],["\u00a0wow lol","bold"]]',true);
$standard = array("bold"=>"b","underline"=>"u","strike"=>"s","italic"=>"i","link"=>"a","size"=>null);
$lists = array("ordered"=>"ol","bullet"=>"ul");
$size = array("huge"=>"2.5em","large"=>"1.5em");
$base = "";
foreach($build as $part){
$use = array();
$tags = true;
$len = 1;
if(!is_array($part) or count($part) == 1){
$text = $part;
$tags = false;
$part = array();
} else {
$text = array_shift($part);
if(count($part) == 1){
if(is_array($part[0])){
$part = $part[0];
}
}
if(!is_array($part)){
$part = array($part);
}
}
if($tags){
foreach ($part as $tag) {
if(!in_array($tag, array_keys($standard)) && !in_array($tag, array_keys($lists)) && !in_array($tag, array_keys($size))){
$base .= '<a href="' . $tag . '" title="' . $tag . '" class="link">';
$tag = "link";
} elseif(in_array($tag, array_keys($size))){
$base .= "<span style='font-size:" . $size[$tag] . "'>";
} elseif(!in_array($tag, array_keys($lists))) {
$base .= "<" . $standard[$tag] . ">";
}
array_push($use, $tag);
}
$base .= $text;
foreach (array_reverse($part) as $tag) {
if(!in_array($tag, array_keys($standard)) && !in_array($tag, array_keys($lists)) && !in_array($tag, array_keys($size))){
$base .= '</a>';
} elseif(in_array($tag, array_keys($size))){
$base .= "</span>";
} elseif (!in_array($tag, array_keys($lists))) {
$base .= "</" . $standard[$tag] . ">";
}
array_push($use, $tag);
}
} else {
$base .= $text;
}
}
print_r($base);

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.

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
}

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