Bir dizideki veri sıralama

4 Cevap

Ben meyve 7 türleri olan bir dizi var:

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

Ben sonuç bu gibi olacak bir şekilde verileri yazdırmak için nasıl bilmiyorum:

<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.

4 Cevap

Bu deneyin:

sort($fruit);
$lastLetter = null;

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

Orada o pasajı, gerektiğinde bazı tidying kalmış, ama fikir olsun.

Bunu yapabilirsiniz:

// 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

Bu sizin için ne arıyorsanız yapmanız gerekir:

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