php - PHP中的一个班轮foreach
问题描述
我的 PHP 代码中有以下函数:
function getFromTable(){ //$sql,$index,$index2,...,$pdo
$args = func_get_args(); // because we don't know how many $index arguments there will be
$sql = $args[0];
$indexes = [];
for ($i=1; $i <count($args)-1; $i++) {
array_push($indexes,$args[$i]);
}
$pdo = $args[count($args)-1]; //penultimate index
$ret = [];
$result = $pdo->prepare($sql);
$result->execute();
foreach($result as $row){
array_push($ret,[$row[$indexes]);
}
return $ret;
}
该函数的目的是从 MySQL 查询中返回行。用户可以选择要返回的索引。由于我不知道索引的数量,我使用 func_get_args() 参数。第一个参数始终是查询,最后一个参数是 PDO,中间的所有参数都是索引。问题出现在 foreach 语句中,我将索引的值推送到数组中。我希望所有索引都在一个数组中,但是我不知道如何在 PHP 中做到这一点。如果是 Python,我会为循环或 lambda 使用一个内衬。PHP中有哪些替代方案?
解决方案
首先,让我们利用 PHP 7.4 的特性,如参数解包和短格式 lambda:
function getFromTable($sql, ...$indices) {
$pdo = array_pop($indices); // Pop the last array entry
$flippedIndices = array_flip($indices); // This is important
$result = $pdo->prepare($sql);
$result->execute();
return array_map(fn ($row) => array_intersect_key($row, $flippedIndices), $result);
}
这是细分:
- 我们编写参数,
$sql, ...$indices
所以我们现在说第一个参数是查询,其余参数是索引。如果参数$sql, $pdo, ...$indices
可以使我们免于需要(2) ,它实际上会更好地工作 $pdo
我们从其余参数中弹出,因为它是最后一个参数。- 从数组中获取特定索引的方法是使用,
array_intersect_key
但要使用它,我们需要传递一个带有我们想要相交的键的数组。array_flip
将实现这一目标。 - 应该将
array_map
所有行映射到仅具有指定键的数组。我们使用 PHP 7.4+ 箭头函数功能,但function ($row) use ($flippedIndices) { return array_intersect_key($row, $flippedIndices); }
如果您想在早期 PHP 版本中使用此代码,您可以使用相同的结果
推荐阅读
- html - 我如何在当前代码中获取子菜单?
- svn - SVN:// 协议在迁移 authz 文件的活动目录后停止工作
- java - @RequestBody 不将请求解析为对象进行验证
- azure-devops - 一次分组和触发多个 Azure 管道
- ios - 在 iOS 11 中应用被用户杀死时的地理围栏
- node.js - 在邮递员数组中发送对象数组始终为空
- python - 我的增强拓扑实现的神经进化无法解决 XOR 问题
- audio - AWS EC2实例上的Pyaudio“无效输入设备(无默认输出设备)”
- ionic3 - 离子范围组件中的自定义事件发射器无法用于生产
- python - 无法在 shopify 中使用 API 创建 webhook