How to efficiently repeat a block of PHP code including a loop? - php

I would like to repeat the following code 15 times or more on a single page:
$html .= '<select name="select_product_category"
class="dropdown_list"><option value="0">All
categories</option>';
foreach($categories as $value) {
$html .= '<option value="' . $value['category_id'] .
'"';
if($value['category_id'] === $active_category_id)
$html .= ' checked';
$html .= '>' . $value['category_name'] . '</option>';
}
$html .= '</select>';
Is there a better way to achieve this than just repeat this particular block of code? Thanks for your support.

Try to use functions as suggested by #Don't Panic
<?php
function generateSelectBoxHTML()
{
$html = '<select name="select_product_category" class="dropdown_list"><option value="0">All categories</option>';
foreach ($categories as $category) {
$checked = '';
if ($category['category_id'] === $activeCategoryId) {
$checked = ' checked="checked"';
}
$html .= sprintf('<option value="%s"%s>%s</option>', $category['category_id'], $checked, $category['category_name']);
}
$html .= '</select>';
return $html;
}
$html .= generateSelectBoxHTML();
// ...
$html .= generateSelectBoxHTML();
$html .= generateSelectBoxHTML();
$html .= generateSelectBoxHTML();

Related

How to add static li inside dynamic list using php?

I have 5 menu in the website which is coming dynamically :
menu1 menu2 menu3 menu4 menu5
Now I want to add menu6 before menu5 using php.
My code:
foreach ($collection as $category) {
$i++;
$menuCategory = $this->getCategoryAsArray($category, $currentCategory);
$class = '';
$class .= 'nav'. $i;
if($i == 1) {
$class .= ' first';
} elseif ($i == $count) {
$class .= ' last';
}
if($menuCategory['is_active']) {
$class .= ' active';
}
//if($this->hasChildProduct($category)) {
//$class .= ' parent';
//}
if($this->hasChildSubCategory($category)) {
$class .= ' parent';
}
$class .= ' level-top';
$html .= '<li class="level0 '. $class .'">';
$html .= '<a href="'. $menuCategory['url'] .'">';
$html .= '<span>'. $menuCategory['name'] .'</span>';
$html .= '</a>';
//if($this->hasChildProduct($category)) {
//$html .= $this->getChildProductMenuHtml($category, $i);
//}
if($this->hasChildSubCategory($category)) {
$html .= $this->getChildSubcategoryMenuHtml($category, $i);
}
$html .= '</li>';
}
Menu6 is the static link which code is:
<li class="vertical-submenu" id="static-menu"><a href="<?php echo $block->getUrl('menu6')?>"><?php echo __('menu6')?></li>
I am not getting the code because i am not aware of values coming in the array in foreach loop.
But I can explain the situation to you via Algorithm.
$i = 0;
foreach(expression){
if(value == "menu5"){
write("Menu 4")
}
Write("Menu ".$i)
$i++;
}
Hope your problem is resolved with this. If you need anything else or want to elaborate more about you problem text me at shahrukhusmaani#gmail.com

PHP Fetch array in table with individual styling

I have an array that i pull from a database that looks like this
id - name - shortlink - downloadurl - count - date
Now I want to display that array as a table so the administartor of the site can se the content of the database. For that, I'm using this code:
function build_table($array){
// start table
$html = '<table id="usertable">';
// header row
$html .= '<tr class="header">';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
And it works great.
The problem is that i wan't do display some of the columns with a different code. E.g. 'downloadurl' which is an webadress, i want to make clickable. I just can't figure out how to split up the function so that i can write the code for the individual columns.
You could try something similar to the following:
using conditionals
This is probably the most straight forward way to go about handling different attributes per column - not without its drawbacks (noted below)
// data rows
foreach( $array as $key => $value) {
$html .= '<tr>';
foreach($value as $key2 => $value2) {
if ($key2 == 'downloadurl') {
$html .= '<td>Download</td>';
} else {
$html .= '<td>' . $value2 . '</td>';
}
}
$html .= '</tr>';
}
using switch statement
If you decide on this route, it may be a bit easier to manage in the long run as if () elseif () else() can become difficult to read over time.
foreach($value as $key2 => $value2) {
switch($key2) {
case 'downloadurl':
$html .= '<td>Download</td>';
break;
default:
$html .= '<td>' . $value2 . '</td>';
}
}
use this function to generate urls:
function getURL($downloadURL)
{
$html = "<a href = '$downloadURL'>Download</a>";
return $html;
}
And your function build_table():
function build_table($array){
// start table
$html = '<table id = "usertable">';
// header row
$html .= '<tr class = "header">';
foreach($array[0] as $key => $value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key => $value){
$html .= '<tr>';
foreach($value as $key2 => $value2){
$value2 = ($key2 == 'downloadurl') ? getURL($value2) : $value2;
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}

How can I echo two items per one time by using PHP Foreach?

I'm using PHP to echo my products from the database. If we just use foreach, we will get the result one item per a loop, but actually I want it echo two items per one times as ub the below function.
This is my PHP function using foreach to fetch data from database.
I've used row item selector to wrap product selector, so I want to echo a block of product two times, and then it should echo the row item.
Example: row item = 1 then product = 2
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
foreach ($data as $k => $row) {
$out .= '<div class="row item">';
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
}
}
return $out;
}
This function will echo one item for a loop.
You can not print two times in one iteration of a loop. You can use conditional HTML output to do this job.
Consider this:
function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
$counter = 1;
$length = count($data);
if ($data) {
foreach ($data as $k => $row) {
if ($counter % 2 != 0) {
$out .= '<div class="row item">';
}
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
if ($counter % 2 == 0 || $length == $counter) {
$out .= '</div>';
}
$counter++;
}
}
return $out;
}
You can use the modulus operator to make the check. If your iterator is a multiple of two it will output the appropriate elements (it does this by checking that the remainder is zero):
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
$i = 0;
foreach ($data as $k => $row) {
if( ($i % 2) === 0) {
$out .= '<div class="row item">';
}
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
if( ($i + 1) % 2 === 0 || ($i + 1) === count($data) ) {
$out .= '</div>';
}
$i++;
}
}
return $out;
}
Note that the last bit ($i + 1) === count($data) is important in the event that your set holds an uneven number.

If in Foreach Loop

I followed a small tutorial and created a chat for a website. I added some features to it, and now individual chats can be saved but I'm not sure how to place an if statement inside the foreach loop. I would like to do something like this: if($chat_message->smgs_id != NULL) { something here } instead of <a class="save" href="#" id="'.$chat_message->id.'">Save</a>
$chat_messages_html = '<ul style="margin:10px;">';
foreach ($chat_messages->result() as $chat_message)
{
$chat_messages_html .= '<li>' . $chat_message->smsg_id . '<a class="save" href="#" id="'.$chat_message->id.'">Save</a> | </li>';
}
$chat_messages_html .= '</ul>';
Ternary for the win!
$html = '<ul>';
foreach ($arr as $val)
{
$html .= '<li>'. (NULL !== $val ? 'something' : 'something else') .'</li>';
}
$html .= '</ul>';
Split the assignment into parts so you can fit in the condition.
$chat_messages_html = '<ul style="margin:10px;">';
foreach ($chat_messages->result() as $chat_message)
{
$chat_messages_html .= '<li>';
if ($chat_message->smgs_id != NULL) {
$chat_messages_html .= '<a class="save" href="#" id="' . $chat_message->id . '">Save</a> | ';
}
$chat_messages_html .= '</li>';
}
$chat_messages_html .= '</ul>';
Try this:
$chat_messages_html = '<ul style="margin:10px;">';
foreach ($chat_messages->result() as $chat_message)
{
if ($chat_message->smgs_id != NULL) {
$chat_messages_html .= '<li>' . $chat_message->smsg_id . '<a class="save" href="#" id="'.$chat_message->id.'">Save</a> | </li>';
}
}
$chat_messages_html .= '</ul>';

Terms by vocabulary in node.tpl

I've created a variable in template.php that let's me print terms by vocabulary. The problem is that I want to be able to pass in a vocabulary id to select a specific vocabulary. My code looks like this:
function xnalaraart_classic_print_terms($node, $vocabularies){
foreach($vocabularies as $vocabulary){
if($terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid)){
$output .= '<div>';
$output .= '<ul class="links inline">';
foreach ($terms as $term){
$output .= '<li class="taxonomy_term_' . $term->tid . '">';
$output .= l($term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description)));
$output .= '</li>';
}
$output .= '</ul>';
$output .= '</div>';
}
}
return $output;
}
and in the preprocess_node function:
$vars['terms_split'] = xnalaraart_classic_print_terms($vars['node']);
How do I write it so that I can pass in an id to $vocabularies?
I think you made this more difficult on yourself than it really is. See below for final function.
function xnalaraart_classic_print_vocab_terms($node, $vid){
if($terms = taxonomy_node_get_terms_by_vocabulary($node, $vid)){
$output .= '<div>';
$output .= '<ul class="links inline">';
foreach ($terms as $term){
$output .= '<li class="taxonomy_term_' . $term->tid . '">';
$output .= l($term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description)));
$output .= '</li>';
}
$output .= '</ul>';
$output .= '</div>';
}
return $output;
}
And then call
$vars['terms_split'] = xnalaraart_classic_print_terms($vars['node'], 10); //Where 10 is the vocab ID

Categories