I got an array 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With