php - 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;
}
解决方案
如何使用array-slice:
while ($row = $result->fetch_assoc()) {
$records[] = array_slice($row, 0, 5);
}
您也可以使用array_filter
(doc):
$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);
}
推荐阅读
- javascript - 旋转游戏玩家
- wordpress - WP All Import Pro:Polylang 兼容性
- mysql - 别名列会受益于索引吗?
- r - ggplot2 不接受 R 中带有 scale_x_continuous 的中断和标签
- dart - 在切换并重新启动应用程序后,如何为 Flutter 中的 Switch 提供正确的值?
- asp.net - MSBUILD:错误 MSB1003:指定项目或解决方案文件。当前工作目录不包含项目或解决方案文件
- webpack - Vue2 webpack 生产构建永远旋转
- css - 最小化浏览器时,inline-block 不会阻止菜单元素重叠
- c# - C# 单元测试卡在 COM 对象上
- symfony - 列出 Symfony 中可用的工作流程