0

I created an array:

$alphabet = range('A', 'Z');

Which created a list of all of the letters of the alphabet. Then I used a for loop to print out all of the letters of the alphabet:

<ul>

<? for ($i = 0; $i < 26; $i++): ?>

    <li><span class="head-menu"><?= $alphabet[$i]; ?></span>

        <ul>

            <li><a href="#">Some Item</a></li>

            <li><a href="#">Some Item</a></li>

        </ul>

    </li>   

<? endfor ?>                

</ul>

In that code, I want to replace:

<li><a href="#">Some Item</a></li>

With a list of values from a database such that the first letter of the value in the name column in the database is the same letter as $alphabet[i].

So for example, if I have a database called "food" with just a "name" field, I want an output as such:

A
    Apple
B
    Banana
C
    Carrots
    Crackers

Where Apple, Banana, Carrots and Crackers are values in the database.

How can I go about doing this?

2 Answers 2

2

What I would do is read your database out into an array and populate it that way

$sql = 'SELECT field FROM table ORDER BY field';
$res = $mysqli->query($sql);
$data = [];
$current = NULL;
while($row = $res->fetch_assoc()) {
    if($row['field']{0} != $current) {
        $current = $row['field']{0};
        $data[$current] = [];
    }
    $data[$current][] = $row['field'];
}

So now you have an array that looks like this

Array( 
    'A' => Array('Apples'),
    'B' => Array('Bananas', 'Blueberries')
    etc
}

Then you just iterate your code

<ul>
<?php for ($i = 0; $i < 26; $i++): ?>
    <li><span class="head-menu"><?= $alphabet[$i]; ?></span>
        <ul>
            <?php foreach($data[$alphabet[$i]] as $fruit): ?>
                <li><a href="#"><?php echo $fruit ?></a></li>
            <?php endforeach ?>
        </ul>
    </li>   
<? endfor ?>                
</ul>
Sign up to request clarification or add additional context in comments.

Comments

0
$alphabet = range('A', 'Z');
$r = mysql_query("SELECT name FROM food");
if ($r) {
    while($row = mysql_fetch_row($r)) {
        $alphabet[$row[0][0]][] = $row[0];
    }
}

For cake

$alphabet = range('A', 'Z');
$food = $this->Food->find('list');
foreach ($food as $v)
    $alphabet[$v[0]][] = $v;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.