developer tip

PHP에 내장 데이터 구조가 있습니까?

optionbox 2020. 12. 4. 08:06
반응형

PHP에 내장 데이터 구조가 있습니까?


내가 찾고 있어요 매뉴얼 PHP , 나는 그런 목록 및 세트 등 대부분의 언어가 가지고있는 데이터 구조에 대한 섹션을 확인할 수 없습니다. 나는 맹인입니까 아니면 PHP에 이와 같은 것이 내장되어 있지 않습니까?


PHP의 유일한 기본 데이터 구조는 배열입니다. 다행히도 배열은 매우 유연하며 해시 테이블로도 사용할 수 있습니다.

http://www.php.net/array

그러나 C ++ STL의 클론 인 SPL이 있습니다.

http://www.php.net/manual/en/book.spl.php


PHP는 표준 PHP 라이브러리 (SPL) 기본 확장을 통해 데이터 구조를 제공하며, 기본적으로 PHP 5.0.0에서 사용 가능하고 컴파일됩니다.

제공되는 데이터 구조는 PHP 5> = 5.3.0에서 사용할 수 있으며 다음을 포함합니다.

이중 연결 목록

이중 연결 목록 (DLL)은 서로 양방향으로 연결된 노드 목록입니다. 반복자의 작업, 양쪽 끝에 대한 액세스, 노드 추가 또는 제거는 기본 구조가 DLL 일 때 O (1)의 비용이 듭니다. 따라서 스택 및 큐에 대한 적절한 구현을 제공합니다.

힙은 힙 속성을 따르는 트리와 같은 구조입니다. 힙에 전역 인 구현 된 비교 메서드를 사용하여 비교할 때 각 노드는 자식보다 크거나 같습니다.

배열

배열은 인덱스를 통해 액세스 할 수있는 연속적인 방식으로 데이터를 저장하는 구조입니다. PHP 배열과 혼동하지 마십시오. PHP 배열은 실제로 정렬 된 해시 테이블로 구현됩니다.

지도

맵은 키-값 쌍을 보유하는 데이터 구조입니다. PHP 배열은 정수 / 문자열에서 값으로의 맵으로 볼 수 있습니다. SPL은 객체에서 데이터로의 맵을 제공합니다. 이 맵은 객체 세트로도 사용할 수 있습니다.

출처 : http://php.net/manual/en/spl.datastructures.php


연관 배열은 대부분의 기본 데이터 구조 해시 테이블, 큐, 스택에 사용할 수 있습니다. 그러나 나무 나 힙과 같은 것을 원한다면 기본적으로 존재한다고 생각하지 않지만 어디에서나 무료 라이브러리가 있다고 확신합니다.

배열이 스택을 에뮬레이트하도록 array_push()하려면 추가 및 array_pop()제거에 사용

배열이 대기열을 에뮬레이트하도록 array_push()하려면 대기열에 넣기 및 대기열 array_shift()에서 빼기

연관 배열은 기본적으로 해시입니다. PHP에서는 문자열을 인덱스로 사용할 수 있으므로 예상대로 작동합니다.

$array['key'] = 'value';

마지막으로 공간을 낭비 할 가능성이있는 배열로 이진 트리를 에뮬레이션 할 수 있습니다. 작은 나무를 갖게 될 것을 안다면 유용합니다. 선형 배열을 사용하여 인덱스 (i)에 대해 왼쪽 자식을 인덱스 (2i + 1)에, 오른쪽 자식을 인덱스 (2i + 2)에 배치한다고 말합니다.

이 모든 방법은 JavaScript 배열이 더 높은 수준의 데이터 구조를 에뮬레이트하는 방법 대해이 기사 에서 설명합니다.


이 질문은 8 살이지만 PHP 7 ds에는 배열의 대안으로 특수 데이터 구조를 제공 하는 확장 기능이 도입 되었기 때문에 답변을 게시하고 있습니다.

ds,

  • Ds\네임 스페이스를 사용합니다 .
  • 3 개의 인터페이스, 즉 Collection, SequenceHashable
  • 이 8 개 클래스, 즉, Vector, Deque, Queue, PriorityQueue, Map, Set, Stack, 및Pair

자세한 내용은 체크 아웃을 위해 매뉴얼 과도 이 블로그 게시물은 벤치 마크 등 일부 멋진 정보가 있습니다.


PHP에는 실제로 연관 배열 인 배열이 있으며 세트로도 사용할 수 있습니다. 많은 해석 언어와 마찬가지로 PHP는 다른 명시 적 데이터 유형을 제공하는 대신이 모든 것을 하나의 후드로 제공합니다.

$lst = array(1, 2, 3);
$hsh = array(1 => "This", 2 => "is a", 3 => "test");

/ 편집 : 또한 설명서를 살펴보십시오 .


PHP의 배열 은 목록과 사전의 두 배가됩니다.

$myArray = array("Apples", "Oranges", "Pears");
$myScalar = $myArray[0] // == "Apples"

또는 연관 배열로 사용하려면 :

$myArray = array("a"=>"Apples", "b"=>"Oranges", "c"=>"Pears");
$myScalar = $myArray["a"] // == "Apples"

데이터 구조가 몇 가지 방향으로 나아 간다고 말할 때 좀 더 구체적으로 말하고 싶을 것 같습니다.

배열-그것들은 확실히 문서화되어 있고 사용 가능합니다. ( http://us.php.net/manual/en/book.array.php )

SQL 데이터-사용중인 데이터베이스에 따라 다르지만 대부분 사용 가능합니다. ( http://us.php.net/manual/en/book.mysql.php )

OOP-버전에 따라 객체를 설계하고 구현할 수 있습니다. ( http://us.php.net/manual/en/language.oop.php ) PHP 사이트에서 이것을 찾기 위해 OOP를 검색해야했습니다.

도움이 되었으면 좋겠습니다. 그렇지 않으면 죄송합니다.


물론 PHP에는 데이터 구조가 있습니다. PHP의 배열은 매우 유연합니다. 몇 가지 예 :

$foo = array(
  'bar' => array(1,'two',3),
  'baz' => explode(" ", "Some nice words")
);

그런 다음 구조를 매핑 / 필터링 / 걷거나 등 변환, 뒤집기, 반전 등을 수행 할 수있는 수많은 배열 함수를 사용할 수 있습니다.


PHP에 특정 유형의 데이터 구조가 포함되어 있지 않다고 생각되면 언제든지 직접 만들 수 있습니다. 예를 들어 다음은 Array가 지원하는 간단한 Set 데이터 구조입니다.

ArraySet : https://github.com/abelperez/collections/blob/master/ArraySet.php

class ArraySet
{
    /** Elements in this set */
    private $elements;

    /** the number of elements in this set */
    private $size = 0;

    /**
     * Constructs this set.
     */ 
    public function ArraySet() {
        $this->elements = array();
    }

    /**
     * Adds the specified element to this set if 
     * it is not already present.
     * 
     * @param any $element
     *
     * @returns true if the specified element was
     * added to this set.
     */
    public function add($element) {
        if (! in_array($element, $this->elements)) {
            $this->elements[] = $element;
            $this->size++;
            return true;
        }
        return false;
    }

    /**
     * Adds all of the elements in the specified 
     * collection to this set if they're not already present.
     * 
     * @param array $collection
     * 
     * @returns true if any of the elements in the
     * specified collection where added to this set. 
     */ 
    public function addAll($collection) {
        $changed = false;
        foreach ($collection as $element) {
            if ($this->add($element)) {
                $changed = true;
            }
        }
        return $changed;
    }

    /**
     * Removes all the elements from this set.
     */ 
    public function clear() {
        $this->elements = array();
        $this->size = 0;
    }

    /**
     * Checks if this set contains the specified element. 
     * 
     * @param any $element
     *
     * @returns true if this set contains the specified
     * element.
     */ 
    public function contains($element) {
        return in_array($element, $this->elements);
    }

    /**
     * Checks if this set contains all the specified 
     * element.
     * 
     * @param array $collection
     * 
     * @returns true if this set contains all the specified
     * element. 
     */ 
    public function containsAll($collection) {
        foreach ($collection as $element) {
            if (! in_array($element, $this->elements)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Checks if this set contains elements.
     * 
     * @returns true if this set contains no elements. 
     */ 
    public function isEmpty() {
        return count($this->elements) <= 0;
    }

    /**
     * Get's an iterator over the elements in this set.
     * 
     * @returns an iterator over the elements in this set.
     */ 
    public function iterator() {
        return new SimpleIterator($this->elements);
    }

    /**
     * Removes the specified element from this set.
     * 
     * @param any $element
     *
     * @returns true if the specified element is removed.
     */ 
    public function remove($element) {
        if (! in_array($element, $this->elements)) return false;

        foreach ($this->elements as $k => $v) {
            if ($element == $v) {
                unset($this->elements[$k]);
                $this->size--;
                return true;
            }
        }       
    }

    /**
     * Removes all the specified elements from this set.
     * 
     * @param array $collection
     *
     * @returns true if all the specified elemensts
     * are removed from this set. 
     */ 
    public function removeAll($collection) {
        $changed = false;
        foreach ($collection as $element) {
            if ($this->remove($element)) {
                $changed = true;
            } 
        }
        return $changed;
    }

    /**
     * Retains the elements in this set that are
     * in the specified collection.  If the specified
     * collection is also a set, this method effectively
     * modifies this set into the intersection of 
     * this set and the specified collection.
     * 
     * @param array $collection
     *
     * @returns true if this set changed as a result
     * of the specified collection.
     */ 
    public function retainAll($collection) {
        $changed = false;
        foreach ($this->elements as $k => $v) {
            if (! in_array($v, $collection)) {
                unset($this->elements[$k]);
                $this->size--;
                $changed = true;
            }
        }
        return $changed;
    }

    /**
     * Returns the number of elements in this set.
     * 
     * @returns the number of elements in this set.
     */ 
    public function size() {
        return $this->size; 
    }

    /**
     * Returns an array that contains all the 
     * elements in this set.
     * 
     * @returns an array that contains all the 
     * elements in this set.
     */ 
    public function toArray() {
        $elements = $this->elements;
        return $elements;   
    }
}

PHP는 또한 "다차원 배열"또는 "행렬"이라고 하는 배열의 배열가질 수 있습니다 . 2 차원 배열, 3 차원 배열 등을 가질 수 있습니다.


데이터 구조의 필수 요구 사항은 SPL (PHP 확장)을 찾아보십시오. 그들은 힙, 연결 목록 등과 같은 데이터 구조를 가지고 있습니다.

PHP가 목록을 가지고 있지 않고 데이터 구조를 정확하게 설정합니다. 그러나 단일 클러스터로 여러 데이터를 제공하는 배열 (n 차원 포함)에 의해 달성 될 수 있습니다.

$variable = array(
  'one' => array(1,'char',3),
  'two' => explode("single", "Multiple strings"),
  'three' => all(9,'nine',"nine")
);

They are not exactly as list or set. But array can replace that. So no need to search for another data structures.


Yes it does.

<?php
$my_array = array("Bird","Cat","Cow");

list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>

http://www.w3schools.com/php/func_array_list.asp


C languages will allow creating a structure and then filling it like a string (char/byte) buffer. Once it's filled the code accesses the buffer via the structure members. It's really nice to parse structured (database,image,etc.) files that way. I don't think you can do that with PHP structures - or am I (hopefully) wrong.

Ok - well PHP does have unpack and pack - functionally the same, but not as elegant.

참고URL : https://stackoverflow.com/questions/22401/does-php-have-built-in-data-structures

반응형