PHP: separate value in array according to alphabate order
i want to find values in array according to alphabate and want to make list in of array values according to alphabat开发者_StackOverflow社区e order.
my array is like that:
Array ( [0] => Array ( [0] => Adidas [1] => AKG [2] => Apple [3] => Barrats [4] => Canon [5] => Dell [6] => Dixons [7] => HTC [8] => Liverpool [9] => Microsoft [10] => Pirelli Tyres [11] => )
)
and i want to make a list of values according to alphabate like this:
A
________
Adidas
AKG
plz any idea?
You're after asort
asort($a);
foreach($a AS $v) {
echo $v . "<br />";
}
Could use some optimization, but does exactly what you asked:
$a = array("Chicken","Fish","Hello","Lebowski","What","hey","foo");
asort($a);
$alphaArr = array();
foreach(range('A', 'Z') as $letter) {
// create empty array at offset for current letter
$alphaArr[$letter] = array();
foreach($a as $item) {
// if the first letter starts with current letter
// push it into subarray
if (substr(strtolower($item),0,1) == strtolower($letter)) {
$alphaArr[$letter][] = $item;
}
}
}
print_r($alphaArr);
Hardly comprehensible question, but I think you are looking for sort
.
$fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); reset($fruits); while (list($key, $val) = each($fruits)) { echo "fruits[".$key."] = ".$val."\n"; }
Your array is already sorted.
Get hold of the inner array and then loop over the values.
Whenever the first letter changes you know its the next letter.
If you want to resort the list by the first letter of the company name, here's one way:
$sorted = array();
foreach($companies as $company) {
$sorted[ strtoupper($company{0}) ][] = $company;
}
Just sort your array using sort()
function and then print it out.
To have these letter captions just substr first letter and then compare to previou one:
$old='';
foreach ($words as $name) {
if ($name[0] != $old) {
echo $name[0]."<hr>\n";
}
echo $name."<br>\n";
$old=$name[0];
}
精彩评论