1

我有以下数组:

Array
(
    [0] => BCD
    [1] => ACE
    [2] => AHP
    [3] => BGH
    [4] => ART
    [5] => COT
    [6] => ARG
    [7] => BGT
)

我需要匹配第一个字母在以下数组中的所有元素:

Array
(
    [0] => B
    [1] => A
)

要得到:

Array
(
    [0] => ACE
    [1] => AHP
    [2] => BGH
    [3] => ART
    [4] => ARG
    [5] => BGT
)

没有循环遍历整个数组,我该如何在 PHP 中执行此操作?是否有内置的 PHP 数组函数或两者的组合?结果数组的键和值的顺序无关紧要。非常感谢。

4

1 回答 1

2

您可以将array_filter用于这些操作:

$array = array('CBD', 'NHN', 'NHP', 'WHC', 'NND', 'CQN', 'WST', 'WVT');

$whitelist = array('W', 'N');

$filtered = array_filter($array, function($val) use ($whitelist) {
  // check if first letter is in the whitelist array
  if (in_array($val{0}, $whitelist)) {
    return $val;
  }
  return false;
});

输出:

Array
(
    [1] => NHN
    [2] => NHP
    [3] => WHC
    [4] => NND
    [6] => WST
    [7] => WVT
)
于 2012-06-15T12:16:18.640 回答