根据分配的变量分解数据库数据和回显结果

Exploding db data and echoing results based on assigned vars

在数据库中 table 我有一些行有 engineid 引擎 ID 为 0 - 6,如果存储了多个引擎,它们将存储为 1:3:5 etc

我有下面的代码,我正在尝试查询数据库并让它提取结果。然后我希望它查询 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));

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

提前致谢

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

<?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));