Wallogit.com
2017 © Pedro Peláez
Collection indexed with objects and scalars
Collection indexed with objects and scalars, (*1)
<?php
$dict = new \DPolac\Dictionary();
$dict[new \stdClass()] = 12;
$dict['php'] = 23;
$dict[100] = 'dictionary';
composer require dpolac/dictionary
Class \DPolac\Dictionary implements Iterator, ArrayAccess,
Countable and Serializable. It also provides methods for
creating and sorting Dictionary and for converting it to array., (*3)
Valid types of keys for Dictionary are: - object - integer - float - string - bool - null, (*4)
You cannot use: - Closure - array, (*5)
To create empty Dictionary, use constructor., (*6)
<?php
$dict = new \DPolac\Dictionary();
You can also create Dictionary from key-value pairs., (*7)
<?php
$dict = \DPolac\Dictionary::fromPairs([
['key1', 'value1'],
['key2', 'value2'],
['key3', 'value3'],
]);
Last option is to create Dictionary from array., (*8)
<?php
$dict = \DPolac\Dictionary::fromArray([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
]);
There are three methods that let you retrieve data as array:, (*9)
Dictionary::keys() - returns array of keys,Dictionary::values() - returns array of values,Dictionary::toPairs() - returns array of key-value pairs; each
pair is 2-element array.Unlike an array, Dictionary is an object and that means it
is reference type. If you want the copy of Dictionary, you have
to use clone keyword or call Dictionary::getCopy() method., (*10)
Just like an array, Dictionary is ordered. To sort Dictionary, use
Dictionary::sortBy($callback, $direction) method. Any argument
can be omitted., (*11)
$callback will be called for every element. Dictionary will
be ordered by values returned by callback.
First argument of the callback is value and second is key of element.
Instead of callable, you can use "values" or "keys" string.$direction can be "asc" or "desc". Default value is "asc".Examples of sorting:, (*12)
<?php
$dictionary->sortBy('values','asc');
<?php
$dictionary->sortBy(function($value, $key) {
return $value->title . $key->name;
}, 'desc');
sortBy changes Dictionary it is called for. If you want sorted copy,
chain it with getCopy., (*13)
<?php
$sortedDictionary = $dictionary->getCopy()->sortBy('values', 'asc');