Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data in an array

Tags:

php

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.

like image 569
kwokwai Avatar asked Mar 20 '26 23:03

kwokwai


2 Answers

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.

like image 132
Amber Avatar answered Mar 23 '26 13:03

Amber


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.

like image 23
nickf Avatar answered Mar 23 '26 11:03

nickf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!