使用Alphabet索引以关联数组的形式重新排列/排序数据

时间:2014-10-26 23:18:05

标签: php arrays sorting

我有一个记录数组(从数据库表中提取的一些类别标题)我想用以下格式对它们进行排序,这样我就可以实现this

之类的东西
$categories = array(
'A' => array(       
            'Abreva',
            'Activia',
            'Advantage',
            'Advil',
            'Air Wick',
            'Ajax',
            'Aleve'),
'B' => array(),

...等等到Z. );

我不知道如何执行此操作但据我所知,它应该是从数据库中获取所有数据后执行的某种排序功能。我已经尝试过我自己但无法达到所需的输出。任何帮助/提示就足够了。提前致谢

3 个答案:

答案 0 :(得分:1)

这应该更有效率:

$sorted = array();
$unsorted = array('Abreva', 'Activia', 'Advantage', 'Advil', 'Ball Park', 'Band-Aid', 'Banquet', 'Barilla', 'Campbells', 'Capri Sun', 'Carefree', 'Caress', 'Dannon', 'Dawn', 'Degree', 'Del Monte', 'Eldership', 'Eldest', 'Xlectre', 'Electrical', 'Facetious', 'Facetiously', 'Facetiousness', 'Facile', 'Gabbler', 'Gabel', 'Gabion', 'Gable', 'Habitableness', 'Habitance', 'Zabitant', 'Habitation', 'Habitator', 'Habitual', '1st Class', '7th Sky');
sort($unsorted);
foreach($unsorted as $item){ // loop array $unsorted as a result from db
    $startchr = ucfirst($item[0]);
    $sorted[is_numeric($startchr)?'0-9':$startchr][] = $item;
}
echo '<pre>';
print_r($sorted); //print sorted
echo '</pre>';

答案 1 :(得分:0)

我们走了......

<?php
$categories=array(); $i=0;
$a=array('fas','abas','ajuma','bizzo','bike','Chacha','cade'); //array, i assume as a data from db

foreach($a as $key=>$value){ // loop array $a as a result from db
if( substr(ucfirst($value),0,1) == 'A'){ 
 //array_push($categories["A"],$value);  // array_push seems not to work 
$categories["A"][]=$value;
 }
if( substr(ucfirst($value),0,1) == 'B'){
 $categories['B'][]=$value;
 }
if( substr(ucfirst($value),0,1) == 'C'){
 $categories['C'][]=$value;
  }
  // .. for C,D ....Z
}
 print_r($categories); //print result
 ?>

您可以复制并查看结果

答案 2 :(得分:0)

在上述评论和答案的帮助下,我已成功解决了问题,感谢@fasM和@JonathanGray

以下是确切的PHP代码

$sorted = array();
$unsorted = array('Abreva', 'Activia', 'Advantage', 'Advil', 'Ball Park', 'Band-Aid', 'Banquet', 'Barilla', 'Campbells', 'Capri Sun', 'Carefree', 'Caress', 'Dannon', 'Dawn', 'Degree', 'Del Monte', 'Eldership', 'Eldest', 'Xlectre', 'Electrical', 'Facetious', 'Facetiously', 'Facetiousness', 'Facile', 'Gabbler', 'Gabel', 'Gabion', 'Gable', 'Habitableness', 'Habitance', 'Zabitant', 'Habitation', 'Habitator', 'Habitual', '1st Class', '7th Sky');
sort($unsorted);
$alphabets = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
foreach($unsorted as $item){ // loop array $unsorted as a result from db
    $inserted = false;
    foreach($alphabets as $alphabet){
        if(substr(ucfirst($item),0,1) == $alphabet){ 
            $sorted[$alphabet][] = $item;
            $inserted = true;
        }
    }
    if($inserted == false){
        $sorted['0-9'][] = $item;
    }
}
echo '<pre>';
print_r($sorted); //print sorted
echo '</pre>';