首页 > 解决方案 > 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

解决方案


首先,让我们利用 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);
}

这是细分:

  1. 我们编写参数,$sql, ...$indices所以我们现在说第一个参数是查询,其余参数是索引。如果参数$sql, $pdo, ...$indices可以使我们免于需要(2) ,它实际上会更好地工作
  2. $pdo我们从其余参数中弹出,因为它是最后一个参数。
  3. 从数组中获取特定索引的方法是使用,array_intersect_key但要使用它,我们需要传递一个带有我们想要相交的键的数组。array_flip将实现这一目标。
  4. 应该将array_map所有行映射到仅具有指定键的数组。我们使用 PHP 7.4+ 箭头函数功能,但function ($row) use ($flippedIndices) { return array_intersect_key($row, $flippedIndices); }如果您想在早期 PHP 版本中使用此代码,您可以使用相同的结果

沙盒链接


推荐阅读