PHP MYSQL Array and sort -


so, have database table has 8 separate category options each customer.

example:

company_name | category_1 | category_2 | category_3 **************************************************** company   | computers  | parts      | electronics 

ect... on 8 category options. need categories in list , list companies category under each category item. have categories array, of them in foreach loop give me duplicates. don't want list duplicates, want list them once , place companies under category.

like:

computers
company name

parts
company name

electronics
company name

ect....

my code currently:

$sql = $wpdb->get_results( "select * $table_name");  echo '<ul>';  foreach ($sql $cat){     $cats[0] = $cat->category_1.' '.$cat->category_2.' '.$cat->category_3.' '.$cat->category_4.' '.$cat->category_5.' '.$cat->category_6.' '.$cat->category_7.' '.$cat->category_8;     $totalcats = $cats[0];     echo '<li>'.$totalcats.'</li>'; }  echo '</ul>'; }// end of foreach loop 

this give me following:

  • computers parts
  • computers electronics
  • electronics parts

ect... each database entry depending on how many categories company chose.

any appreciated!

i don't have dataset test should work. create multidimensional array dataset this:

[comp][0] = company       [1] = company b       ... [elec][0] = company       [1] = company c       ... [part][0] = company y       [1] = company z       ... 

then iterate on print out.

<?php $cats = array();  // loop through rows foreach($sql $cat) {     // loop through row categories    for($i=1; $i<=8; ++$i) {        // column name       $column = 'category_'.$i;        // column has data       // $cats[category][irrelevant index] = company name       if($cat->$column !== null && $cat->$column !== '') {          $cats[$cat->$column][] = $cat->company_name;       }    } }  // sort categories ksort($cats);  echo '<ul>';  // loop though categories foreach($cats $catname=>$cat) {     // sort companies in category    sort($cat);     // category name    echo '<li>'.$catname.'</li><ul>';     // loop through companies    foreach($cat $company) {       echo '<li>'.$company.'</li>';    }     echo '</ul>'; } echo '</ul>'; ?> 

it best store categories in separate table , start there, using join retrieve associated company names. require less code print out way want it.

update 2015-07-09 10:02 +0000

changed column data testing $cat->$column !== ''

update 2015-07-09 10:49 +0000

changed column data testing $cat->$column !== null && $cat->$column !== '' based on wpdb results structure.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -