PHP - Ds Vector::slice() 函式



PHP 的 Ds\Vector::slice() 函式用於從原始向量中檢索給定範圍內的子向量。子向量是原始向量的一部分。例如,向量 {1, 2} 是原始向量 {1, 2, 3} 的子向量。

此函式接受一個名為“length”的可選引數。以下是關於此引數的關鍵點列表:

  • 如果“length”為負數,則向量停止從末尾計算那麼多元素。
  • 如果“length”為正數,則子向量包含那麼多元素。
  • 如果“length”超過向量大小,則只包含直到向量末尾的值。
  • 如果未提供“length”,則子向量將包含“index”和向量末尾之間的所有值。

語法

以下是 PHP Ds\Vector::slice() 函式的語法:

public Ds\Vector::slice(int $index, int $length = ?): Ds\Vector

引數

以下是此函式的引數:

  • index - 子向量開始提取的索引。
  • length - 子向量的長度。

返回值

此函式返回給定範圍內的子向量。

示例 1

以下是 PHP Ds\Vector::slice() 函式的基本示例:

<?php   
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);  
   echo("The original vector: \n");   
   print_r($vector);
   $index = 1;
   $length = 2;
   echo "The index and length is: ".$index.", ".$length;
   #using slice() function
   $result = $vector->slice(1, 2); 
   echo("\nThe new sub-vector:\n");  
   print_r($result);
?>

輸出

上述程式產生以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The index and length is: 1, 2
The new sub-vector:
Ds\Vector Object
(
    [0] => 2
    [1] => 3
)

示例 2

如果長度為負數,向量將停止從末尾計算那麼多值。

以下是 PHP Ds\Vector::slice() 函式的另一個示例。我們使用此函式從給定範圍 (1, -2) 的原始向量中檢索子向量:

<?php 
   $vector = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo("The original vector: \n");
   print_r($vector);
   $index = 1;
   $length = -2;
   echo "The index and length is: ".$index.", ".$length;
   $result = $vector->slice(1, -2);
   echo("\nThe new sub-vector: \n");
   print_r($result);
?>

輸出

執行上述程式後,將顯示以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The index and length is: 1, -2
The new sub-vector:
Ds\Vector Object
(
    [0] => 20
    [1] => 30
)

示例 3

如果長度值超過向量大小,則只包含直到向量末尾的值。

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo("The original vector: \n");
   print_r($vector);
   $index = 0;
   $length = 10;
   echo "The index and length is: ".$index.", ".$length;
   $result = $vector->slice($index, $length);
   echo("\nThe new sub-vector: \n");
   print_r($result);
?>

輸出

執行上述程式後,將顯示以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The index and length is: 0, 10
The new sub-vector:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)

示例 4

如果沒有提供長度,則結果向量將包含索引和向量末尾之間的所有值。

<?php 
   $vector = new \Ds\Vector(['a', 'e', 'i', 'o', 'u']);
   echo("The original vector: \n");
   print_r($vector);
   $index = 2;
   echo "The index is: ".$index;
   $result = $vector->slice($index);
   echo("\nThe new sub-vector: \n");
   print_r($result);
?>

輸出

以下是上述程式的輸出:

The original vector:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The index is: 2
The new sub-vector:
Ds\Vector Object
(
    [0] => i
    [1] => o
    [2] => u
)
php_function_reference.htm
廣告