2026-10-22 20:56:43
PHP 提供了多种数据结构实现方式,以下为完整指南:
一、数组和哈希表PHP 数组本质是哈希表,支持数字索引和键值对存储。
自定义哈希表示例:
class HashTable { private $table = []; public function put($key, $value) { $index = hash('sha256', $key); $this->table[$index] = $value; } public function get($key) { $index = hash('sha256', $key); return $this->table[$index] ?? null; }}// 使用示例$hash = new HashTable();$hash->put('username', 'admin');echo $hash->get('username'); // 输出: admin二、链表适合动态数据存储,包含单向链表和双向链表实现。
单向链表示例:
class ListNode { public $data; public $next = null;}class LinkedList { private $head = null; public function append($data) { $newNode = new ListNode(); $newNode->data = $data; if ($this->head === null) { $this->head = $newNode; } else { $current = $this->head; while ($current->next !== null) { $current = $current->next; } $current->next = $newNode; } } public function get($index) { $current = $this->head; $count = 0; while ($current !== null) { if ($count === $index) return $current->data; $count++; $current = $current->next; } return null; }}三、堆栈和队列遵循 LIFO(堆栈)和 FIFO(队列)原则。
堆栈实现:
class Stack { private $stack = []; public function push($item) { array_push($this->stack, $item); } public function pop() { if (empty($this->stack)) return null; return array_pop($this->stack); } public function peek() { return end($this->stack); }}队列实现:
class Queue { private $queue = []; public function enqueue($item) { array_push($this->queue, $item); } public function dequeue() { if (empty($this->queue)) return null; return array_shift($this->queue); }}四、树结构包括二叉树、二叉搜索树等实现。
二叉搜索树示例:
class TreeNode { public $data; public $left = null; public $right = null;}class BinarySearchTree { private $root = null; public function insert($data) { $newNode = new TreeNode(); $newNode->data = $data; if ($this->root === null) { $this->root = $newNode; } else { $this->insertNode($newNode, $this->root); } } private function insertNode($node, &$subtree) { if ($subtree === null) { $subtree = $node; } elseif ($node->data < $subtree->data) { $this->insertNode($node, $subtree->left); } else { $this->insertNode($node, $subtree->right); } } public function search($data) { return $this->searchNode($data, $this->root); } private function searchNode($data, $node) { if ($node === null) return false; if ($data === $node->data) return true; return $data < $node->data ? $this->searchNode($data, $node->left) : $this->searchNode($data, $node->right); }}五、图结构适合表示复杂关系网络。
邻接表图实现:
class Graph { private $vertices = []; public function addVertex($vertex) { $this->vertices[$vertex] = []; } public function addEdge($vertex1, $vertex2) { $this->vertices[$vertex1][] = $vertex2; $this->vertices[$vertex2][] = $vertex1; // 无向图 } public function getVertices() { return array_keys($this->vertices); } public function getEdges($vertex) { return $this->vertices[$vertex] ?? []; }}六、性能优化建议PHP 标准库已内置部分数据结构:
通过合理选择数据结构,可以显著提升 PHP 应用的性能和可维护性。