Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP/CakePHP-从数据库创建值列表_Php_Mysql_Cakephp_Cakephp 2.0 - Fatal编程技术网

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

PHP/CakePHP-从数据库创建值列表,php,mysql,cakephp,cakephp-2.0,Php,Mysql,Cakephp,Cakephp 2.0,我创建了一个数组: $alphabet = range('A', 'Z'); 它创建了字母表中所有字母的列表。然后我使用for循环打印出字母表中的所有字母: <ul> <? for ($i = 0; $i < 26; $i++): ?> <li><span class="head-menu"><?= $alphabet[$i]; ?></span> <ul>

我创建了一个数组:

$alphabet = range('A', 'Z');
它创建了字母表中所有字母的列表。然后我使用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>
其中苹果、香蕉、胡萝卜和饼干是数据库中的值


我该怎么做呢?

我要做的是将您的数据库读取到一个数组中,并以这种方式填充它

$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'];
}
现在有了一个如下所示的数组

Array( 
    'A' => Array('Apples'),
    'B' => Array('Bananas', 'Blueberries')
    etc
}
然后您只需迭代代码

<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');
$food = $this->Food->find('list');
foreach ($food as $v)
    $alphabet[$v[0]][] = $v;
<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];
    }
}
$alphabet = range('A', 'Z');
$food = $this->Food->find('list');
foreach ($food as $v)
    $alphabet[$v[0]][] = $v;