首页 > 解决方案 > sql查询后仅将某些字段添加到数组

问题描述

我只想将第 1 到第 5 项添加到$records(第 6 项用于其他用途)。下面的代码将添加所有六个项目。如何只添加前五个?

$TheQuery="SELECT Item1, Item2, Item3, Item4, Item5, Item6 FROM MyTable";
$result = $link->query($TheQuery);

while ($row = $result->fetch_assoc()) {
    $records[]=$row;
}

标签: phparrays

解决方案


如何使用array-slice

while ($row = $result->fetch_assoc()) {
    $records[] = array_slice($row, 0, 5);
}

您也可以使用array_filterdoc):

$keys = array("Item1", "Item2", "Item3", "Item4", "Item5");
while ($row = $result->fetch_assoc()) {
    $records[] = array_filter($row, function ($key) use ($keys ) {
        return in_array($key, $keys); }, ARRAY_FILTER_USE_KEY);
}

推荐阅读