【问题标题】:find all the negative numbers in the array using array_map php使用array_map php查找数组中的所有负数
【发布时间】:2015-08-20 04:59:11
【问题描述】:

我有这个测试数组

$test = array(-10,20,40,-30,50,-60);

我希望输出是

$out = array (-10, -30, -60);

这是我的解决方案:

$temp = array();

function neg($x)
{
    if ($x <0) 
    {
        $temp[] = $x; 
        return $x;
    }
}
$negative = array_map("neg", $test);

当我打印$negative 时,我得到了我想要的东西,但有些条目是空的。我可以在回调函数中做些什么来不记录空条目吗?

Array
(
    [0] => -10
    [1] => 
    [2] => 
    [3] => -30
    [4] => 
    [5] => -60
)
1

当我打印$temp 数组时,我以为我会得到答案,但它打印了一个空数组。我不明白为什么,我正在清除将$x 添加到我的回调函数中的$temp[] 数组。有什么想法吗?

print_r($temp);
// outputs
Array
(
)
1

【问题讨论】:

  • 你不想要array_map...你想要array_filter
  • @Orangepill 但是这与 array_map 无关,对吧?我将值 $x 存储在回调函数中可访问的 $temp 数组中。
  • 见例子here
  • $temp的范围在回调中。
  • 为什么会这样?我在回调之外声明了 $temp,并且每次调用回调时都将 $x 附加到 $temp。?

标签: php arrays callback array-map


【解决方案1】:

array_map 将在条件满足时返回value,如果条件不满足则返回NULL。在这种情况下,您可以使用array_filter

$test = array(-10,20,40,-30,50,-60);

$neg = array_filter($test, function($x) {
    return $x < 0;
});

输出

array(3) {
  [0]=>
  int(-10)
  [3]=>
  int(-30)
  [5]=>
  int(-60)
}

如果您继续使用array_map,那么我建议您在完成后申请一次array_filter -

$negative = array_map("neg", $test);
$negative = array_filter($negative);

输出将是相同的。

【讨论】:

  • 这很好,回答了我的一个问题,但是为什么 $temp 数组没有被填充到我的回调函数中?
  • $temp 由于作用域的原因,仅在函数内部可用。你不能像那样访问它们。尽管无论如何都不需要$temp
猜你喜欢
  • 2017-01-28
  • 1970-01-01
  • 2013-04-25
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多