PHP - Ds\PriorityQueue::toArray() 函式



PHP 的 Ds\PriorityQueue::toArray() 函式用於將佇列轉換為陣列。因此,該函式返回一個包含優先順序佇列中所有專案的陣列。

語法

以下是 PHP Ds\PriorityQueue::toArray() 函式的語法:

public array Ds\PriorityQueue::toArray( void )

引數

toArray() 函式不接受任何引數。

返回值

此函式返回一個包含所有值的陣列,順序與佇列相同。

PHP 版本

toArray() 函式從 Ds 擴充套件的 1.0.0 版本開始可用。

示例 1

在這裡,我們將向您展示 PHP Ds\PriorityQueue::toArray() 函式將優先順序佇列轉換為陣列的基本示例。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();  
   
   $pqueue->push("Tutorials", 1); 
   $pqueue->push("Point", 2); 
   $pqueue->push("India", 3); 
  
   echo "The equivalent array is: \n"; 
   print_r($pqueue->toArray());
?>

輸出

以上程式碼將產生類似以下的結果:

The equivalent array is: 
Array
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)

示例 2

現在,以下程式碼使用 toArray() 函式建立已建立的 PriorityQueue 的空陣列。

<?php
   // Import the PriorityQueue class
   use Ds\PriorityQueue;

   // Create a new PriorityQueue
   $pqueue = new PriorityQueue();
   
   $array = $pqueue->toArray();
   print_r($array);  
?> 

輸出

這將建立以下輸出:

Array
(
)

示例 3

在下面的 PHP 程式碼中,我們將嘗試使用 toArray() 函式並新增具有不同優先順序的元素,並將佇列更改為陣列。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();  

   $pqueue->push("low priority", 1);
   $pqueue->push("medium priority", 5);
   $pqueue->push("high priority", 10);
   
   $array = $pqueue->toArray();
   print_r($array);
?> 

輸出

這將生成以下輸出:

Array
(
    [0] => high priority
    [1] => medium priority
    [2] => low priority
)

示例 4

在以下示例中,我們使用 toArray() 函式將陣列作為專案新增到優先順序佇列中,並將其轉換為陣列。

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   $pqueue->push(["task" => "A", "priority" => 1], 1);
   $pqueue->push(["task" => "B", "priority" => 2], 2);
   $pqueue->push(["task" => "C", "priority" => 3], 3);
   
   $array = $pqueue->toArray();
   print_r($array);
?> 

輸出

以下是以上程式碼的輸出:

Array
(
    [0] => Array
        (
            [task] => C
            [priority] => 3
        )

    [1] => Array
        (
            [task] => B
            [priority] => 2
        )

    [2] => Array
        (
            [task] => A
            [priority] => 1
        )

)
php_function_reference.htm
廣告