Domanda

Sto guardando il Manuale PHP, e non vedo una sezione sulle strutture dati presenti nella maggior parte dei linguaggi, come elenchi e insiemi.Sono semplicemente cieco o PHP non ha nulla di simile integrato?

È stato utile?

Soluzione

L'unica struttura dati nativa in PHP è l'array.Fortunatamente, gli array sono abbastanza flessibili e possono essere utilizzati anche come tabelle hash.

http://www.php.net/array

Tuttavia, esiste SPL che è una sorta di clone di C++ STL.

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

Altri suggerimenti

PHP offre strutture dati tramite l'estensione di base Standard PHP Library (SPL), disponibile e compilata per impostazione predefinita in PHP 5.0.0.

Le strutture dati offerte sono disponibili con PHP 5 >= 5.3.0 e includono:

Elenchi doppiamente collegati

Una lista doppiamente collegata (DLL) è una lista di nodi collegati tra loro in entrambe le direzioni.Le operazioni dell'iteratore, l'accesso ad entrambe le estremità, l'aggiunta o la rimozione di nodi hanno un costo pari a O(1) quando la struttura sottostante è una DLL.Fornisce quindi un'implementazione decente per stack e code.

Cumuli

Gli heap sono strutture ad albero che seguono la proprietà heap:ogni nodo è maggiore o uguale ai suoi figli, se confrontato utilizzando il metodo di confronto implementato che è globale nell'heap.

Array

Gli array sono strutture che memorizzano i dati in modo continuo, accessibili tramite indici.Non confonderli con gli array PHP:Gli array PHP sono infatti implementati come tabelle hash ordinate.

Carta geografica

Una mappa è una struttura dati che contiene coppie chiave-valore.Gli array PHP possono essere visti come mappe da numeri interi/stringhe a valori.SPL fornisce una mappa dagli oggetti ai dati.Questa mappa può essere utilizzata anche come set di oggetti.

Fonte: http://php.net/manual/en/spl.datastructures.php

L'array associativo può essere utilizzato per la maggior parte delle strutture dati di base, tabella hash, coda e stack.Ma se vuoi qualcosa come un albero o un heap, non penso che esistano per impostazione predefinita, ma sono sicuro che ci siano librerie gratuite ovunque.

Per fare in modo che un array emuli uno stack utilizzare array_push() aggiungere e array_pop() decollare

Per fare in modo che un array emuli una coda utilizzare array_push() accodare e array_shift() togliere la coda

Un array associativo è un hash per impostazione predefinita.In PHP è consentito avere stringhe come indici, quindi funziona come previsto:

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

Infine, puoi emulare un albero binario con un array con il potenziale per avere spazio sprecato.È utile se sai che avrai un piccolo albero.Usando un array lineare, dici che per qualsiasi indice (i) metti il ​​figlio sinistro nell'indice (2i+1) e il figlio destro nell'indice (2i+2).

Tutti questi metodi sono ben descritti Questo articolo su come fare in modo che gli array JavaScript emulino strutture dati di livello superiore.

Sebbene questa domanda abbia 8 anni, sto pubblicando una risposta perché PHP 7 introduce un'estensione chiamata ds fornire strutture dati specializzate come alternativa all'array.

IL ds,

  • utilizza il Ds\ spazio dei nomi.
  • ha 3 interfacce vale a dire,Collection, Sequence E Hashable
  • ha 8 classi vale a dire, Vector, Deque,Queue, PriorityQueue, Map, Set, Stack, E Pair

Per ulteriori informazioni controlla il Manuale e anche Questo post sul blog ha alcune informazioni fantastiche inclusi i benchmark.

PHP dispone di array che in realtà sono array associativi e possono anche essere utilizzati come set.Come molti linguaggi interpretati, PHP offre tutto questo sotto un unico cappuccio invece di fornire diversi tipi di dati espliciti.

Per esempio.

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

/Modificare:Inoltre, dai un'occhiata nel manuale.

PHP vettore funge sia da elenco che da dizionario.

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

Oppure per usarlo come un array associativo:

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

Penso che potresti voler essere un po' più specifico, quando dici strutture di dati la mia mente va in alcune direzioni...

Array: sono certamente ben documentati e disponibili in.(http://us.php.net/manual/en/book.array.php)

Dati SQL: dipende dal database in uso, ma la maggior parte è disponibile.(http://us.php.net/manual/en/book.mysql.php)

OOP - A seconda della versione è possibile progettare e realizzare oggetti.(http://us.php.net/manual/en/lingual.oop.php) Ho dovuto cercare OOP per trovarlo sul sito php.

Spero che questo aiuti, scusa se non è così.

Ovviamente PHP ha strutture dati.L'array in php è incredibilmente flessibile.Qualche esempio:

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

Quindi hai a disposizione un'assoluta pletora di funzioni di array per mappare/filtrare/percorrere/ecc. le strutture, o convertire, capovolgere, invertire, ecc.

Puoi sempre crearne uno tuo se non ritieni che PHP includa un tipo specifico di struttura dati.Ad esempio, ecco una semplice struttura di dati Set supportata da un Array.

Set di array: 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 può anche avere un file serie di matrici che è chiamato "array multidimensionale" o "matrice".Puoi avere array bidimensionali, array tridimensionali, ecc.

Per la necessità obbligatoria di strutture dati consultare il SPL(Estensioni PHP).Stanno avendo strutture di dati come heap, elenco collegato, ..eccetera...

PHP non ha l'elenco e imposta esattamente le strutture dei dati.ma possono essere ottenuti tramite array (con n dimensioni), che forniscono più dati con un singolo cluster

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

Non sono esattamente come nell'elenco o nell'insieme.Ma l'array può sostituirlo.Quindi non è necessario cercare altre strutture dati.

Sì, lo fa.

<?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

I linguaggi C consentiranno di creare una struttura e quindi di riempirla come un buffer di stringhe (caratteri/byte).Una volta riempito, il codice accede al buffer tramite i membri della struttura.È davvero bello analizzare file strutturati (database, immagini, ecc.) in questo modo.Non penso che tu possa farlo con le strutture PHP - o mi sbaglio (si spera).

Ok, beh PHP ha unpack e pack: funzionalmente uguali, ma non così eleganti.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top