Add links within a foreach loop - php

I have a loop which displays the tags, I'd like to add an anchor link to those tags. My code is as follows:
<?php $brands = get_the_tags(); ?>
<p class="brand-tags">
<?php
$count = 0;
foreach ($brands as $brand) {
// echo sizeof($brands);
if ($count < sizeof($brands)-1) {
echo $brand->name.', ';
$count += 1;
}
else {
echo $brand->name;
}
}
?>
</p>

Try this
$brands = get_the_tags();
$links = array();
foreach($brands as $_brand){
$links[] = ''.$_brand->name.'';
}
echo join(', ', $links);

I assume you want to add link to brand name? Here is the code for that:
<?php $brands = get_the_tags(); ?>
<p class="brand-tags"><?php
$count = 0;
foreach ($brands as $brand) {
// echo sizeof($brands);
if ($count < sizeof($brands)-1) {
echo ''.$brand->name.' ';
$count += 1;
} else {
echo ''.$brand->name.' ';
}
} ?></p>

Related

alphabetising table data using arrays / if statements

I have some data that I'm looping through and alphabetizing using if statements. My code works but the problem is it seems like a very "long way around". I'd like to know if there's another approach that I'm missing that could make this much easier.
Here's my PHP:
// MY QUERY
$query1 = "SELECT `categoryid`, `categoryname`
FROM `my_table_category`
ORDER BY `my_table_category`.`categoryname` ASC";
$browse = mysql_query($query1) or die(mysql_error());
$browse_rows = array();
while($row = mysql_fetch_assoc($browse)){
$browse_rows[] = $row;
}
// HERE MY ARRAYS FOR THE ALPHABET
$list_a = array(); $list_b = array(); $list_c = array();
$list_d = array(); $list_e = array(); $list_f = array();
$list_g = array(); $list_h = array(); $list_i = array();
// etc...
// HERE IS WHERE I'M GRABBING THE CATEGORY NAMES BY THEIR FIRST LETTER
// AND ADDING THEM TO AN ARRAY
foreach($browse_rows as $row){
if($row['categoryname'][0] == 'A'){
$list_a[] = $row['categoryname'];
}elseif($row['categoryname'][0] == 'B'){
$list_b[] = $row['categoryname'];
}elseif($row['categoryname'][0] == 'C'){
$list_c[] = $row['categoryname'];
}elseif($row['categoryname'][0] == 'D'){
$list_d[] = $row['categoryname'];
}
} //etc...
Here is my HTML:
<!-- HERE IS HOW I DISPLAY MY DATA -->
<div id="topics_a">
<h2>A</h2>
<ul class="browse_list">
<?
foreach($list_a as $name){
if ($holdcat <> $name) {
$holdcat = $name; ?>
<li><a href="index.php?state="<? echo $template->State."#".$browse_row['categoryid'];?>><? echo $name; ?></a></li>
<? }} ?>
</ul>
</div>
<div id="topics_b">
<h2>B</h2>
<ul class="browse_list">
<?
foreach($list_b as $name){
if ($holdcat <> $name) {
$holdcat = $name; ?>
<li><a href="index.php?state="<? echo $template->State."#".$browse_row2['categoryid'];?>><? echo $name; ?></a></li>
<? }} ?>
</ul>
</div>
//etc...
Updated after the answer:
//UPDATED PHP
foreach ($browse_rows as $row) {
$initial = $row['categoryname'][0];
$lists[$initial][] = $row['categoryname'];
}
//UPDATED HTML
<? foreach ($lists as $letter => $list){ ?>
<div>
<h2><? echo $letter; ?></h2>
<ul class="browse_list">
<?
$list = array_unique($list);
foreach ($list as $cat) {
?>
<li><? echo $cat; ?></li>
<? } ?>
</ul>
</div>
<? } ?>
Output:
http://d.pr/i/bt68
Use a multidimensional array, not separate arrays for each letter.
$lists = array();
foreach ($browse_list as $row) {
$initial = $row['categoryname'][0];
if (!isset($row[$initial])) {
$lists[$initial] = array();
}
$lists[$initial][] = $row['categoryname'];
}
Then when you want to display it, sort the array by the keys, then use nested loops:
ksort($lists);
foreach ($lists as $list) {
echo '<ul class="browse_list">';
$list = array_unique($list); // get rid of duplicates
foreach ($list as $cat) {
echo '<li>' . $cat . '</li>';
}
echo '</ul>';
}

PHP - Drop down not showing all items in mysql

I am Trying to make a drop down menu, and list multiple items as well.
like for example:
here is my database:
if you see in that image you can see only one of the rows have a parent if i want multiple rows to have a parent of 'Far Far Away123' it only shows one of the items
<?php
function build_dropdown ($parent, $pages){
$items = "";
foreach($pages as $page){
// $items = "";
if($page['parent'] == $parent){
$items = $page;
} // END if
} // END foreach
if(is_array($items)){ // If a sub
echo '<ul id="sub_menu" class="sub_navagation'. $items['id'] .'">';
echo '<li>'.$items['page_name'].'</li>';
echo '</ul>';
} // END if
}// End Function
$sql = "SELECT * FROM pages ORDER by item_order";
$result = mysqli_query($db, $sql);
confirm_query($result);
while ($row = mysqli_fetch_assoc($result)) {
$pages[] = $row; // Add each row to $pages array to use later
}
foreach($pages as $key => $page){
if($page['parent'] == 'none'){ ?>
<li id = "<?php echo $page['id']; ?>">
<a href="page.php?id=<?php echo $page['id']; ?>" title="<?php echo $page['page_title']; ?>">
<?php echo $page['page_name']; ?>
</a>
<?php ?>
<?php
} // END if
build_dropdown($page['page_name'], $pages); // If there are child items then build them out
echo "</li> ";
} // END foreach
?>
Thanks
It is because you add only one.
You have a foreach searching all pages for subitems and remember only one of them for the latter if (is_array())
function build_dropdown($parent, $pages)
{
// item is an array
$items = array();
foreach($pages as $page) {
if ($page['parent'] == $parent) {
// add an element to the array
$items[] = $page;
} // END if
} // END foreach
if ($items) {
echo '<ul id="sub_menu" class="sub_navagation">';
foreach ($items as $item) {
echo '<li>'.$item['page_name'];
build_dropdown($item['page_name'], $pages);
echo '</li>';
} // END foreach
echo '</ul>';
} // END if
}// End Function
By the way, it would be better to start with the function giving build_dropdown($parent = 'none', $pages)
Try this inside your buildDropdown() function..
$items = array();
foreach($pages as $page)
{
if($page['parent'] == $parent)
{
$items[] = $page;
}
}
if (count($items) > 0)
{
echo '<ul id="sub_menu_'.$parent.'" class="sub_navagation">';
foreach($items as $item)
{
echo '<li>'.$item['page_name'].'</li>';
}
echo '</ul>';
}

Split array into div [duplicate]

This question already has answers here:
Break PHP array into 3 columns
(7 answers)
Closed 7 years ago.
I have this array :
$result = array('description1', 'description2', 'description3', 'description4', 'description5'
I want to split this array into divs like this :
$result[0] - $result[1] => put these into a div
$result[2] - $result[3] => put these into a div
$result[4] => put this into a div
My entire structure
$content = get_the_content();
$description = array();
$j=0;
if (preg_match_all('/<div id="description" class="description">([^<]*)<\/div>/', $content, $match)) {
for( $i = 0; $i < count($match[0]); $i = $i+1 ) {
$description[] = $match[0][$i];
}
}
$attachments =& get_children($args);
$arrayMatches = array();
if ($attachments) {
foreach(array_chunk($attachments, 2) as $img) {
echo '<div class="two_cols">';
foreach($img as $attachment) {
foreach($attachment as $attachment_key => $attachment_value) {
$imageID = $attachment->ID;
$imageTitle = $attachment->post_title;
$imagearray = wp_get_attachment_image_src($attachment_value, $size, false);
$imageAlt = get_post_meta($imageID, '_wp_attachment_image_alt', true);
$imageURI = $imagearray[0]; // 0 is the URI
$imageWidth = $imagearray[1]; // 1 is the width
$imageHeight = $imagearray[2]; // 2 is the height
?>
<div class="col_1_2">
<!-- A picure Here -->
<?php $arrayMatches[] = $match[0][$j]; ?>
</div>
<?php
break;
}
$j++;
}
$arrayMatches = array_chunk($arrayMatches, 2);
echo "<div>";
foreach($arrayMatches as $v) {
echo implode($v);
}
echo "</div>";
echo '</div>';
}
}
This should work for you:
Just chunk your array with array_chunk(). And then you can simply loop through your array, output it into a div and implode() the elements.
<?php
$result = array('description1', 'description2', 'description3', 'description4', 'description5');
$result = array_chunk($result, 2);
foreach($result as $v) {
echo "<div>" . implode(" ", $v) . "</div>";
}
?>
output:
<div>description1 description2</div>
<div>description3 description4</div>
<div>description5</div>
EDIT:
As from your updated array structure just grab all values first like this:
$result = [];
$arr = array(['description1'], ['description2'], 'description3', 'description4', 'description5'); //example
array_walk_recursive($arr, function($v, $k)use(&$result){
$result[] = $v;
});
$result = array_chunk($result, 2);
Can you not just echo them in divs:
<div>
<?php echo $result[0] . "-" . $result[1]; ?>
</div>
<div>
<?php echo $result[2] . "-" . $result[3]; ?>
</div>
<div>
<?php echo $result[4]; ?>
</div>
You just need to control whether you are in the last 2 positions or not.
echo '<div>';
for ($i=0;$i<count($result);$i=$i+2) {
if ($i+1 >= count($result)) {
echo $result[$i];
} else {
echo $result[$i].$result[$i+1];
echo '</div><div>';
}
}
echo '</div>;

start end div after some elements php

I cannot solve problem with starting ending divs after couple of elements from array.
What i want to get is something like that:
<div>
element1
element2
element3
element4
</div>
<div>
element5
element6
element7
element8
</div>
<div>
element9
element10
</div>
Here is my php code:
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$perRow = 4;
$count = 1;
foreach ($array as $arr){
// here div needs to start, use 4 elements from array and close
if($count % $perRow == 0 OR $count == 1){
echo '<div>';
}
echo $arr . '<br>';
// here should div close
$count++;
}
Try something like this
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$perRow = 4;
$count = 0;
echo '<div>';
foreach ($array as $arr){
// here div needs to start, use 4 elements from array and close
if($count % $perRow == 0 && $count!=0){
echo '</div><div>';
}
echo $arr . '<br>';
// here should div close
$count++;
}
echo '</div>';
Okay I am not familiar with arrays and maybe something like this would work:
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$i=0;
echo '<div>'
if (i<3) {
echo '$array[$i]';
$i++;
}
echo '</div>';
echo '<div>';
if ($i>3 && $i<7) {
echo '$array[$i]';
$i++;
}
echo '</div>';
echo '<div>';
if ($i>7 && $i<10) {
echo '$array[$i]';
$i++;
}
echo '</div>';

PHP loop, change last item?

This might actually be a css question but I'm hoping not because I'd like this to work in IE.
I have the following loop:
<?php
if ($category)
{
foreach($category as $item)
{
echo $item['name'];
echo ", ";
}
} ?>
Which should output
item, item, item, item,
The only thing is...I'd like to NOT have a comma after the last item. Is there any way to do this within a loop?
Well to keep your code how it is, you could add a counter, and skip the last one.
<?php
if ($category) {
$counter = 0;
foreach($category as $item)
{
$counter++;
echo $item['name'];
if ($counter < count($category)) {
echo ", ";
}
}
}
?>
Or you can do it much, much, quicker:
<?php echo implode(", ", array_map(create_function('$item', 'return $item["name"];'), $category)); ?>
Don't echo immediately but save your output into a variable that you can trim.
<?php
if ($category) {
$output = '';
foreach($category as $item) {
$output .= $item['name'];
$output .= ", ";
}
echo rtrim($output, ', ');
}
?>
The implode solution is the simplest, but you asked for a loop. This method avoids putting an extra conditional in the loop, and therefore should be somewhat more efficient. Basically, instead of doing something different for the last item, you do something different for the first item.
$myArray = array(); //Fill with whatever
$result = $myArray[0];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx];
}
EDIT: After realizing you want $item['name'] instead of just $item:
$myArray = array(); //Fill with whatever
$result = $myArray[0]['name'];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx]['name'];
}
As lovely as foreach is,...
<?php
if ($category) {
$count = count($category) - 1;
for ($i = 0; $i <= $count; $i++) {
echo $category[$i]['name'];
if ($i < $count)
echo ', ';
}
}
?>
...for is sometimes necessary.
Assuming $category is an array, you can use implode to get what you want:
Edit: Missed the $categories['name'] part, this should work:
<?php implode(", ", array_keys($category, 'name')); ?>
The standard solution to the "last comma" problem is to put items into an array and then implode it:
$temp = array();
foreach($category as $item)
$temp[] = $item['name'];
echo implode(', ', $temp);
If you want this more generic, you can also write a function that picks ("plucks") a specific field out of each subarray:
function array_pluck($ary, $key) {
$r = array();
foreach($ary as $item)
$r[] = $item[$key];
return $r;
}
and then just
echo implode(', ', array_pluck($category, 'name'));
Or you could check for the last key:
end($category);
$lastkey = key($category);
foreach ( $category AS $key => $item ) {
echo $item['name'];
if ( $lastkey != $key ) {
echo ', ';
}
}
And another option:
<?php
$out = "";
foreach ($category as $item)
{
$out .= $item['name']. ", ";
}
$out = preg_replace("/(.*), $/", "$1", $out);
echo $out;
?>

Categories