简体   繁体   English

PHP / CakePHP - 从数据库创建值列表

[英]PHP / CakePHP - Creating a list of values from a database

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: 然后我使用for循环打印出字母表中的所有字母:

<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]. 使用数据库中的值列表,使得数据库中名称列中值的第一个字母与$ alphabet [i]的字母相同。

So for example, if I have a database called "food" with just a "name" field, I want an output as such: 因此,例如,如果我有一个名为“food”的数据库只有一个“name”字段,我想要一个输出:

A
    Apple
B
    Banana
C
    Carrots
    Crackers

Where Apple, Banana, Carrots and Crackers are values in the database. Apple,Banana,Carrots和Crackers在数据库中的价值所在。

How can I go about doing this? 我该怎么做呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM