PHP Ds Deque filter()函数用法介绍

2021年3月12日13:00:36 发表评论 783 次浏览

Ds \ Deque :: filter()function是PHP中的内置函数, 用于根据回调函数中定义的操作从双端队列中滤除元素。

语法如下:

public Ds\Deque::filter( $callback ) : Ds\Deque

参数:该函数接受单个参数$ callback这是回调函数, 其中包含对双端队列元素的过滤器的定义。

返回值:此函数返回一个新的Deque, 此Deque包含回调返回True的所有值, 或者如果未提供回调则转换为True的所有值。

下面的程序说明了Ds \ Deque :: filter()PHP中的功能:

程序1:

<?php
  
// Creating a deque
$deque = new \Ds\Deque([1, 2, 3, 4, 5, 6]);
  
echo ( "Elements in the deque are\n" );
  
print_r( $deque );
  
// Use filter() function to filter 
// the elements as per requirement
print_r( $deque ->filter( function ( $value ) {
     return $value % 2 == 0;
}));
  
?>

输出如下:

Elements in the deque are
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Ds\Deque Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)

程式2:

<?php
  
// Creating a deque
$deque = new \Ds\Deque([10, 20, 3, 40, 50, 6]);
  
echo ( "Elements in the deque are\n" );
  
print_r( $deque );
  
// Use filter() function to filter 
// the elements as per requirement
print_r( $deque ->filter( function ( $value ) {
     return $value % 10 != 0;
}));
  
?>

输出如下:

Elements in the deque are
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 3
    [3] => 40
    [4] => 50
    [5] => 6
)
Ds\Deque Object
(
    [0] => 3
    [1] => 6
)

参考: http://php.net/manual/en/ds-deque.filter.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: