Sorting data in an array
I got an array开发者_Python百科 which has 7 types of fruit:
$fruits = array(
"lemon",
"orange",
"banana",
"apple",
"cherry",
"apricot",
"Blueberry"
);
I don't know how to print out the data in a way that the outcome will like this:
<A>
Apple, Apricot <!--(Note that Apricot is followed by Apple in alphabetic order)-->
<B>
Banana
<C>
Cherry
<L>
Lemon
<O>
Orange
I am sorry that the question may be a bit difficult. But please kindly help if you could.
I'd first use an array sorting function like sort()
, and then create a loop that goes through the array and keeps track of what the first letter of the last word it output is - each time the first letter changes, output a new heading first.
Try this:
sort($fruit);
$lastLetter = null;
foreach ($fruit as $f) {
$firstLetter = substr($f, 0, 1);
if ($firstLetter != $lastLetter) {
echo "\n" . $firstLetter . "\n";
$lastLetter = $firstLetter;
}
echo $f . ", ";
}
There's some tidying up needed from that snippet, but you get the idea.
You can do this:
// make the first char of each fruit uppercase.
for($i=0;$i<count($fruits);$i++) {
$fruits[$i] = ucfirst($fruits[$i]);
}
// sort alphabetically.
sort($fruits);
// now create a hash with first letter as key and full name as value.
foreach($fruits as $fruit) {
$temp[$fruit[0]][] = $fruit;
}
// print each element in the hash.
foreach($temp as $k=>$v) {
print "<$k>\n". implode(',',$v)."\n";
}
Working example
This should do what you are looking for:
$fruits = array("lemon","orange","banana","apple","cherry","apricot","Blueberry");
//place each fruit in a new array based on its first character (UPPERCASE)
$alphaFruits = array();
foreach($fruits as $fruit) {
$firstChar = ucwords(substr($fruit,0,1));
$alphaFruits[$firstChar][] = ucwords($fruit);
}
//sort by key
ksort($alphaFruits);
//output each key followed by the fruits beginning with that letter in a order
foreach($alphaFruits as $key=>$fruits) {
sort($fruits);
echo "<{$key}>\n";
echo implode(", ", $fruits)."\n";
}
精彩评论