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



PHP 的 Ds\PriorityQueue::jsonSerialize() 函式用於返回可以轉換為 JSON 的表示形式。我們永遠不應該直接呼叫此函式。

語法

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

public Ds\PriorityQueue::jsonSerialize(): array

引數

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

返回值

此函式返回一個表示元素的陣列。

PHP 版本

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

示例 1

首先,我們將向您展示 PHP Ds\PriorityQueue::jsonSerialize() 函式的基本示例,以瞭解其工作原理。

<?php
   // Create a new priority queue
   $queue = new \Ds\PriorityQueue();
   
   // Add some elements with priorities
   $queue->push("apple", 2);
   $queue->push("banana", 1);
   $queue->push("cherry", 3);
   
   // Convert the priority queue to JSON
   $json = json_encode($queue->jsonSerialize());
   
   // Display the JSON string
   echo $json;
?>

輸出

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

["cherry","apple","banana"]

示例 2

現在,我們將使用 jsonSerialize() 函式處理巢狀的優先順序佇列並顯示結果。

<?php
   // Create a new PriorityQueue
   $queue1 = new \Ds\PriorityQueue();
   $queue2 = new \Ds\PriorityQueue();
   
   // Add elements to the first queue
   $queue1->push("apple", 2);
   $queue1->push("banana", 1);
   
   // Add the first queue to the second queue
   $queue2->push($queue1, 3);
   $queue2->push("cherry", 2);
   
   // Serialize the outer priority queue to JSON
   $json = json_encode($queue2->jsonSerialize());
   
   // Display the JSON string
   echo $json;
?> 

輸出

這將生成以下輸出:

[["apple","banana"],"cherry"]

示例 3

現在,在下面的程式碼中,我們將使用 jsonSerialize() 函式序列化並顯示按優先順序排序的元素,並將其打印出來。

<?php
   // Create a new PriorityQueue
   $queue = new \Ds\PriorityQueue();
   
   // Add elements with different priorities
   $queue->push("task1", 5);
   $queue->push("task2", 2);
   $queue->push("task3", 8);
   
   // Serialize the priority queue to JSON
   $json = json_encode($queue->jsonSerialize());
   
   // Display the JSON string
   echo $json;
?> 

輸出

這將建立以下輸出:

["task3","task1","task2"]

示例 4

在下面的示例中,我們使用 jsonSerialize() 函式新增帶有其優先順序的自定義物件。

<?php
   class Task {
      public $name;
      public $designation;
  
      public function __construct($name, $designation) {
          $this->name = $name;
          $this->designation = $designation;
      }
  }
  
  // Ensure the Ds extension is enabled
  $queue = new \Ds\PriorityQueue();
  
  // Add custom objects with priorities
  $queue->push(new Task("Amit", "Engineer"), 2);
  $queue->push(new Task("Deepak", "Doctor"), 1);
  $queue->push(new Task("Sakshi", "Teacher"), 3);
  
  // Serialize the priority queue to JSON
  $json = json_encode($queue->jsonSerialize());
  
  // Display the JSON string
  echo $json;
?> 

輸出

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

[{"name":"Sakshi","designation":"Teacher"},{"name":"Amit","designation":"Engineer"},{"name":"Deepak","designation":"Doctor"}]
php_function_reference.htm
廣告