PHP - 从数组中删除不需要的元素


PHP - Remove Unwanted Elements From Array

假设我有一个如下所示的数组。

[0] => Array
    [0] => Peter drives 45km to work
    [1] => Tom rides 32km with his friends
    [2] => Lisa walks 6km to the gym
    [3] => Bob cycles 12km to keep fit
    [4] => Bill takes the train 63km to work
    [5] => Penny runs 8km to the shop
    [6] => Robert takes a taxi 21km to the museum

假设我只想保留在 10-15 公里之间旅行的人,并从数组中删除所有其他人员。另外,假设我想使用的范围是可变的,即:今天我可能想看看谁在 10-15 公里之间旅行,但明天我可能想看看谁在 5-15 公里之间旅行,然后第二天我可能想看看谁在 30-50 公里之间旅行。

我将如何搜索此数组并删除所有不在我指定范围内的元素,或者将我需要的元素移动到新数组中?

关于我需要的元素,我需要保留整个值,而不仅仅是行进的距离。

您可以将 php 的数组过滤器函数与使用正则表达式从字符串中提取相关数字的回调结合使用:

<?php
$min = 10;
$max = 20;
$input = [
  "Peter drives 45km to work",
  "om rides 32km with his friends",
  "Lisa walks 6km to the gym",
  "Bob cycles 12km to keep fit",
  "Bill takes the train 63km to work",
  "Penny runs 8km to the shop",
  "Robert takes a taxi 21km to the museum",
];
$output = array_filter($input, function($string) use ($min, $max) {
  preg_match('/([0-9]+)km/', $string, $matches);
  $number = intval($matches[1]);
  return ($number>$min) && ($number<$max);
});
print_r($output);

此示例的输出(给定的 $min$max 值)为:

Array
(
    [3] => Bob cycles 12km to keep fit
)

不同的方法是可能的,在这里我使用了"闭包"来保持紧凑。显然,$min$max 中的值是您想要以动态方式定义的值。应在回调函数中添加一些错误处理,以防输入字符串具有意外的格式。我把它留在这里,以再次保持紧凑......

如果从数组中删除任何项目。

unset($a[2]);

$a是包含数组的变量。