krak/array

缺失的 PHP 数组函数集合

v0.4.3 2017-12-19 03:44 UTC

This package is auto-updated.

Last update: 2024-09-18 19:56:44 UTC


README

数组库只是一个简单的缺失 PHP 数组函数集合。

安装

使用 composer 在 krak/array 下安装

使用方法

<?php

use Krak\Arr;

$data = [
    'a' => [
        'b' => 1,
    ],
];

$res = Arr\get($data, 'a.b');
assert($res == 1);

Arr\set($data, 'c.d', 2);
assert($data['c']['d'] == 2);

// or use the global aliases
array_get($data, 'a.b');

还有一个名为 Bag 的类,它为数组提供了一个面向对象的 API。

<?php

use Krak\Arr;

$bag = new Arr\Bag();
$bag->set('a.b', 1);
var_dump($bag->raw());
/*
    array(1) {
      ["a"]=>
      array(1) {
        ["b"]=>
        int(1)
      }
    }
*/

API

以下定义在命名空间 Krak\Arr

array expand(iterable $iterable, string $separator = '.')
array index_by(iterable $iterable, string $key)
array udiff_stable(iterable $a, iterable $b, callable $cmp)
mixed get(array $data, string $key, mixed $else = null)
mixed getIn(array $data, array $key, mixed $else = null);
bool has(array $data, string $key, string $sep = '.')
bool hasIn(array $data, array $key)
void set(array &$data, string $key, mixed $value, string $sep = '.')
void del(array &$data, string $key, string $sep = '.')

您也可以使用全局定义的别名

array_expand
array_index_by
array_udiff_stable
array_get
array_has
array_set
array_del

或者使用 Krak\Arr\Bag

<?php

namespace Krak\Arr;

class Bag implements ArrayAccess {
    public function __construct(array $data = [])
    public function get($key, $else = null, $sep = '.')
    public function getIn(array $key, $else = null)
    public function set($key, $value, $sep = '.')
    public function has($key, $sep = '.')
    public function hasIn(array $key)
    public function del($key, $sep = '.')
    public function raw()
}

测试

使用 phpunit 运行测试