alphabetising table data using arrays / if statements - php

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

Related

How do I generate a custom menu wp_get_nav_menu_items into Fourth level?

how can I turn this function from Two-level into the Fourth level in WordPress?
This function can only echo the parent and it's child, but I'm trying to make it unlimited or at lest 4 level if it possible
A
B -2
C -2
-3
-4
D -2
F
this is my code:
function wp_get_menu_array($current_menu) {
$array_menu = wp_get_nav_menu_items($current_menu);
$menu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
$menu[$m->ID] = array();
$menu[$m->ID]['ID'] = $m->ID;
$menu[$m->ID]['title'] = $m->title;
$menu[$m->ID]['url'] = $m->url;
$menu[$m->ID]['children'] = array();
}
}
$submenu = array();
foreach ($array_menu as $m) {
if ($m->menu_item_parent) {
$submenu[$m->ID] = array();
$submenu[$m->ID]['ID'] = $m->ID;
$submenu[$m->ID]['title'] = $m->title;
$submenu[$m->ID]['url'] = $m->url;
$menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
}
}
return $menu;
}
$menu_items = wp_get_menu_array('main-menu'); // Then call in your theme
<nav>
<ul>
<?php foreach ($menu_items as $item) : ?>
<li>
<?= $item['title'] ?>
<?php if( !empty($item['children']) ):?>
<ul class="sub-menu">
<?php foreach($item['children'] as $child): ?>
<li class="b-main-header__sub-menu__nav-item">
<?= $child['title'] ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
<ul>
</nav>

How do I get to the third level of nested children in this PHP array?

I have built a simple php function that retrieves a Wordpress menu and converts it to a readable array. Here's my code:
function wp_get_menu_array($current_menu) {
$array_menu = wp_get_nav_menu_items($current_menu);
$menu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
$menu[$m->ID] = array();
$menu[$m->ID]['ID'] = $m->ID;
$menu[$m->ID]['title'] = $m->title;
$menu[$m->ID]['url'] = $m->url;
$menu[$m->ID]['children'] = array();
}
}
$submenu = array();
foreach ($array_menu as $m) {
if ($m->menu_item_parent) {
$submenu[$m->ID] = array();
$submenu[$m->ID]['ID'] = $m->ID;
$submenu[$m->ID]['title'] = $m->title;
$submenu[$m->ID]['url'] = $m->url;
$menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
}
}
return $menu;
}
What I would like to achieve, is a further (#submenu2) that will iterate through $submenu, check if any of those are post parents, and insert their children under them in the array.
In other words: This array currently creates a relationship like this:
(if parent has no children, assign these values)
(if parent has children, iterate through children and add these values)
I want to add
(if child has children, iterate through children and add these values).
Any pointers as to where/how the third loop would go, I would greatly appreciate it.
Thank you in advance!
The problem of building a tree from a flat array has been solved here with this, slightly modified, recursive solution:
function buildTree( array &$elements, $parentId = 0 )
{
$branch = array();
foreach ( $elements as &$element )
{
if ( $element->menu_item_parent == $parentId )
{
$children = buildTree( $elements, $element->ID );
if ( $children )
$element->wpse_children = $children;
$branch[$element->ID] = $element;
unset( $element );
}
}
return $branch;
}
$array_menu = wp_get_nav_menu_items('main-menu'); //put the menu slug here
$menu = buildTree( $array_menu );
echo '<pre>';
print_r($menu);
Is that much of code is really required ?
You may check following code -
wp_get_nav_menu_items( 'Your_Manu_ID' )
Work for me:
<nav>
<ul>
<?php $itens_menu = wp_get_menu_array("principal"); ?>
<?php
$menu_corrente = 0;
foreach($itens_menu as $menu){
if($menu_corrente==0) $classe = "todos-os-produtos";
if($menu_corrente==1) $classe = "home";
if($menu_corrente>1) $classe = "";
if(count($menu["children"])==0):
?>
<li class="sou-categoria-<?php echo $menu["ID"] ?>"><a class="<?php echo $classe; ?>" href="<?php echo $menu["url"]; ?>" title=""><?php echo $menu["title"]; ?></a></li>
<?php
else:
?>
<li class="sou-categoria-<?php echo $menu["ID"] ?>"><a class="<?php echo $classe; ?>" href="<?php echo $menu["url"]; ?>" title=""><?php echo $menu["title"]; ?></a>
<ul>
<?php
foreach($menu["children"] as $submenu){
?>
<li><?php echo $submenu["title"]; ?>
<?php echo terceiro_nivel("principal",$submenu["ID"]); ?>
</li>
<?php
}
?>
</ul>
</li>
<?php
endif;
$menu_corrente++;
}
?>
<li>
<i class="fa fa-search"></i>
</li>
<li>
<a href="<?php echo get_option('home'); ?>/carrinho" title="Meu Carrinho" class="btn btn-primary">
<i class="fa fa-shopping-cart " aria-hidden="true"></i> Carrinho: <span>
<?php
global $woocommerce;
echo $woocommerce->cart->get_cart_total();
?>
</span>
</a>
</li>
</ul>
</nav>
In functions.php:
function wp_get_menu_array($current_menu) {
$array_menu = wp_get_nav_menu_items($current_menu);
$menu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
$menu[$m->ID] = array();
$menu[$m->ID]['ID'] = $m->ID;
$menu[$m->ID]['title'] = $m->title;
$menu[$m->ID]['class'] = $m->class;
$menu[$m->ID]['url'] = $m->url;
$menu[$m->ID]['children'] = array();
}
}
$submenu = array();
foreach ($array_menu as $m) {
if ($m->menu_item_parent) {
$submenu[$m->ID] = array();
$submenu[$m->ID]['ID'] = $m->ID;
$submenu[$m->ID]['title'] = $m->title;
$submenu[$m->ID]['class'] = $m->class;
$submenu[$m->ID]['url'] = $m->url;
$menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
}
}
return $menu;
}
// HABILITAR O TERCEIRO NÍVEL DE SUBMENUS AO MENU PRINCIPAL
function terceiro_nivel($current_menu,$idMenu){
$array_menu = wp_get_nav_menu_items($current_menu);
$menu = array();
$i = 0;
$saida = "";
foreach ($array_menu as $m) {
if ($m->menu_item_parent == $idMenu) {
if($i==0){
$saida = $saida.'
<ul class="terceiro-nivel">
<div>
';
$i++;
}
$saida = $saida.'<li class="valide-'.$m->menu_item_parent.'">'.$m->title.'</li>';
}
}
if($i!=0){
$saida = $saida.' </div>
</ul>';
}
return $saida;
}

Add links within a foreach loop

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>

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

Group MySQL results into blocks of A-Z in PHP

I have a list of thousands of results and I want to group them alphanumerically for example, I need it to be like this:
<h1>0-9</h1>
<ul>
<li>011example</li>
<li>233example</li>
<li>65example</li>
</ul>
<h1>A</h1>
<ul>
<li>albert</li>
<li>alfred</li>
<li>annie</li>
</ul>
<h1>B</h1>
<ul>
<li>ben</li>
<li>bertie</li>
<li>burt</li>
</ul>
But I can't work out how to split or group my results into 0-9 and A-Z.
Currently I have:
<?php
$get_az = mysql_query("SELECT custom_22 FROM db_table1");
echo '<ul>';
while ($row = mysql_fetch_assoc($get_az)) {
$getfirstletter = substr($row['custom_22'], 0,1);
$name = $row['custom_22'];
echo '<h1>'.$getfirstletter.'</h1>';
echo '<li>'.$name.'</li>';
}
echo '</ul>';
?>
Order by the name and handle each letter one by one.
$get_az = mysql_query("SELECT custom_22 FROM db_table1 ORDER BY custom_22 ASC");
$current_first_letter = null;
while ($row = mysql_fetch_assoc($get_az)) {
$first_letter = strtolower(substr($row['custom_22'], 0, 1));
if (preg_match("/[0-9]/", $first_letter)) { // detect digits
$first_letter = "0-9";
}
if ($first_letter !== $current_first_letter) {
if ($current_first_letter !== null) {
echo '</ul>';
}
echo '<h1>' . $first_letter . '</h1>';
echo '<ul>';
}
$current_first_letter = $first_letter;
echo '<li>' . htmlentities($row['custom_22']) . '</li>';
}
if ($current_first_letter !== null) {
echo '</ul>';
}
I would do it this readable way:
$get_az = mysql_query('SELECT custom_22 FROM db_table1 ORDER BY custom_22');
$groups = array();
split results to groups
while ($row = mysql_fetch_assoc($get_az)) {
$firstLetter = strtolower(substr($row['custom_22'], 0, 1));
check for digits
if (is_numeric($firstLetter)) {
$firstLetter = '0-9';
}
if (isset($groups[$firstLetter]) === false) {
$groups[$firstLetter] = array();
}
$groups[$firstLetter][] = $row['custom_22'];
}
simply iterate over groups and echoes it
foreach ($groups as $h1 => $items) {
echo sprintf('<h1>%s</h1>', strtoupper(htmlspecialchars($h1)));
echo '<ul>';
foreach ($items as $item) {
echo sprintf('<li>%s</li>', htmlspecialchars($item));
}
echo '</ul>';
}

Categories