按键值对PHP数组进行分组

时间:2013-01-09 10:42:10

标签: php object grouping

基本上我正在尝试像这样分组我的数组:

Shopping
   Amazon
Social
   Amoeblo
   American express

使用以下PHP代码:

<?php

echo '<ul id="list"><h2 class="searchresults"></h2>';
foreach($records as $catval) {
  $sitechar = $catval->site_category; 
  echo '<h3 id="disappear">'. strtoupper($sitechar) .'</h3>';       
  echo '<li class="siteli"><a href="#" class="add">'; 
  echo '<p id="text-site">'.$catval->site_name. '</p></a>';
  echo '</li>'; 
}
echo '</ul>';
?>

但是我的价值只有如下。

Shopping
       Amazon
Social
       Amoeblo
Social
       American express

我没有得到用于此的确切PHP排序。

3 个答案:

答案 0 :(得分:2)

我会创建一个新数组,其中类别为带有网站的数组的键。

<?php
$arr = array();

// First create multidimensional array with categories as keys for site arrays
foreach($records as $catval) {
    $sitechar = $catval->site_category;
    if (!array_key_exists($sitechar, $arr)) {
        // Set new array for a category if it does not exist
        $arr[$sitechar] = array();
    }

    // Add site to category
    $arr[$sitechar][] = array(
        "name"=>$catval->site_name,
        "image"=>$catval->site_img
    );
}

// Then iterate the new array of categories
echo ("<ul>");
foreach($arr as $category => $sites) {
    echo("<h3>" . $site_category "</h3>");

    // Iterate array of sites
    foreach($sites as $site) {
        echo("<li>" . $site["name"] . "-" ,  $site["image"] . "</li>");
    }
}
echo("</ul>");
?>

答案 1 :(得分:1)

你可以使用foreach和ksort

来做到这一点

让$ your_array成为您上面提到的数组

$res_array    = array();
foreach($your_array as $val){
   $res_array[$val->site_category][] = $val->site_name;
}
ksort($res_array);

print_r($res_array);

或者在php中搜索multisort来解决你的问题:)

答案 2 :(得分:0)

$tmp = null;

   echo '<ul id="list"><h2 class="searchresults"></h2>';
     foreach($records as $catval) {
       $myHtml = makeHtml($catval,$tmp);
       echo  $myHtml;
      $tmp = $catval->site_category;
     }
   echo '</ul>';


 function makeHtml($catval,$tmp){
       if($tmp != $catval->site_category){ $html .= '<h3 id="disappear">'. strtoupper($catval->site_category) .'</h3>';}
       $html .='<li class="siteli"><a href="#" class="add"><p id="text-site">'.$catval->site_name. '</p></a></li>'; 
       return $html;
 }