Sort data in an array

I have an array that has 7 types of fruits:

$fruits = array(
  "lemon", 
  "orange", 
  "banana", 
  "apple", 
  "cherry", 
  "apricot", 
  "Blueberry"
);

I do not know how to print the data so that the result is as follows:

<A>
Apple, Apricot <!--(Note that Apricot is followed by Apple in alphabetic order)-->
<B>
Banana
<C>
Cherry
<L>
Lemon
<O>
Orange

I'm sorry the question can be a little tricky. But please kindly help if you could.

+3
source share
4 answers

First I used the array sort function, for example sort(), and then I create a loop that goes through the array and keeps track of the fact that the first letter of the last word that it outputs is every time the first letter changes, first print a new header.

+2
source

Try the following:

sort($fruit);
$lastLetter = null;

foreach ($fruit as $f) {
    $firstLetter = substr($f, 0, 1);
    if ($firstLetter != $lastLetter) {
        echo "\n" . $firstLetter . "\n";
        $lastLetter = $firstLetter;
    }
    echo $f . ", ";
}

This fragment requires some recycling, but you get the idea.

+2
source

:

// 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";
}

+2

, :

    $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";   
}
+2

Source: https://habr.com/ru/post/1743135/


All Articles