爆炸数据库数据并根据分配的变量回显结果

时间:2017-10-06 13:36:09

标签: php arrays explode

在数据库表中,我有行有engineid的行 引擎ID为0 - 6,如果存储多个引擎,则存储为1:3:5等

我有下面的代码,我正在尝试查询数据库并让它拉取结果。然后我想让它查询engineid列,在以下位置展开它:然后将每个值分配给另一个变量(参见下面的代码)

    $itemsq = mysqli_query($con,"SELECT * FROM `crm`.`service-items` WHERE `itemgroup` = 'Service' LIMIT 0,10");
$items = mysqli_fetch_assoc($itemsq);
do {
$enginetype = explode(":",$items);
$eng0 = "engine_Sigma engine_K-Series engine_Duratec engine_Suzuki engine_Vauxhall engine_Crossflow";
$eng1 = "engine_Sigma";
$eng2 = "engine_K-Series";
$eng3 = "engine_Duratec";
$eng4 = "engine_Suzuki";
$eng5 = "engine_Vauxhall";
$eng6 = "engine_Crossflow";

$enginetype[0] = $eng0;
$enginetype[1] = $eng1;
$enginetype[2] = $eng2;
$enginetype[3] = $eng3;
$enginetype[4] = $eng4;
$enginetype[5] = $eng5;
$enginetype[6] = $eng6;

echo  "$items[code] - ".$enginetype;

} while($items = mysqli_fetch_assoc($itemsq));

希望这对你们有意义。 请不要问我为什么使用:分离数据,它不是我的数据库,当我开始在这里工作时就像这样

提前致谢

1 个答案:

答案 0 :(得分:0)

在数组中定义引擎,而不是单个变量,然后从数组中选择结果中的引擎。

<?php
$eng[] = "engine_Sigma engine_K-Series engine_Duratec engine_Suzuki engine_Vauxhall engine_Crossflow";
$eng[] = "engine_Sigma";
$eng[] = "engine_K-Series";
$eng[] = "engine_Duratec";
$eng[] = "engine_Suzuki";
$eng[] = "engine_Vauxhall";
$eng[] = "engine_Crossflow";

$items = '1:3:5';
$enginetype = explode(":", $items);

/*
engine_Sigma
engine_Duratec
engine_Vauxhall
*/
foreach ($enginetype as $key) {
    echo $eng[$key].PHP_EOL;
}

https://3v4l.org/utBNG

您的代码如下:

<?php
// define engines - add a numeric key if you need it
$eng[] = "engine_Sigma engine_K-Series engine_Duratec engine_Suzuki engine_Vauxhall engine_Crossflow";
$eng[] = "engine_Sigma";
$eng[] = "engine_K-Series";
$eng[] = "engine_Duratec";
$eng[] = "engine_Suzuki";
$eng[] = "engine_Vauxhall";
$eng[] = "engine_Crossflow";

// query your db
$itemsq = mysqli_query($con,"SELECT * FROM `crm`.`service-items` WHERE `itemgroup` = 'Service' LIMIT 0,10");

// do/while? should prob just use a while loop
do {
    $enginetype = explode(":", $items);

    foreach ($enginetype as $key) {
        echo "\$eng[$key] - ".$eng[$key].PHP_EOL;
    }

} while ($items = mysqli_fetch_assoc($itemsq));