mfn/util-simpleorderedmap

接受任意键的有序映射

v0.0.2 2014-09-27 07:17 UTC

This package is auto-updated.

Last update: 2024-09-16 16:45:58 UTC


README

主页: https://github.com/mfn/php-util-simpleorderedmap

基本用法

$map = new \Mfn\Util\Map\SimpleOrderedMap;
$map->add(new \stdClass, "value");
foreach ($map->keys() as $key) {
  echo $map->get($key), PHP_EOL;
}

输出: value

常见用法

添加和设置键/值

use \Mfn\Util\Map\SimpleOrderedMap;
$map = SimpleOrderedMap;
$map->add($key, $val); # throws exception if key already exists
$map->set($key, $val); # replaces value if key already exists

检索

$val = $map->get($key); # throws exception if key does not exist
if ($map->exists($key)) {
  # ...
}

移除

$map->del($key); # throws exception if key does not exist

在移除时,键总是保持其顺序,这个位置索引是可用的

$index = $map->getKeyPosition($key);
$key = $map->getKayAt($index);
$val = $map->getValueAt($index);

从现有的散列表或数组创建

use \Mfn\Util\Map\SimpleOrderedMap;
$map = SimpleOrderedMap::fromHash(['a'=>true,10=>NULL]);
$map->keys(); # ['a',10]
$map->values(): # [true,NULL]

# The same with separate arrays. Note: arrays length must match
$map = SimpleOrderedMap::fromArrays(
  ['a',10],
  [true,NULL]
);
$map->keys(); # ['a',10]
$map->values(): # [true,NULL]

更多方法,请参阅SimpleOrderedMap的源代码

与键/值验证一起使用

如果您需要某种类型的验证,可以使用SimpleOrderedValidatingMap,它提供了检查新添加的键和值的回调函数

use Mfn\Util\Map\SimpleOrderedValidatingMap as Map;

$map = new Map(
              function($key) {
                if ($key instanceof \stdClass) {
                  return;
                }
                throw new \Mfn\Util\Map\SimpleOrderedValidatingMapException(
                  'Only keys of type stdClass are allowed'
                );
              },
              function($value) {
                if ($value instanceof \stdClass) {
                  return;
                }
                throw new \Mfn\Util\Map\SimpleOrderedValidatingMapException(
                  'Only values of type stdClass are allowed'
                );
              }
           );
# Throws an exception
$map->add(1,2);

安装

使用composer: composer.phar require mfn/util-simpleorderedmap 0.0.2

贡献

将其Fork,在功能分支上开发,创建一个Pull Request

© Markus Fischer markus@fischer.name