celyes/ray

PHP中的数组操作

0.0.1 2023-10-19 17:42 UTC

This package is auto-updated.

Last update: 2024-09-19 23:10:15 UTC


README

🇵🇸巴勒斯坦的孩子们需要您的帮助!在此捐款 here 🇵🇸

Ray是一个简单的库,提供了流畅而优雅的语法来访问数组中的元素。

Ray的一些功能包括访问第一个元素、最后一个元素、特定元素,并且它还可以在嵌套数组中工作。

安装

您可以通过composer包管理器安装Ray。

composer require celyes/ray

用法

以下代码包含了一些如何使用这个简单库的示例。

// create a Ray object from any array...
$array = Ray::from([
    'first' => ['foo' => 'bar'],
    'second' => ['bar' => 'baz'],
    1 => [2, 3]
])

// Access elements however you like

echo $array->first()->last(); // bar.
echo $array->nth(1)->last(); // baz

echo $array->get('first')->get('foo')->key(); // foo
echo $array->get('first')->get('foo')->value(); // bar

// we called value since it's not a string + PHP does not offer a magic method similar to __toString when it comes to numeric values.
echo $array->last->nth(1)->value(); // 3

遍历值

您可以使用each()方法遍历Ray对象的值。该方法接受一个可调用的函数,将在数组的每个元素上执行。请注意,此方法会原地更改数组。

以下是一个示例

$array = Ray::from([
    'first' => ['foo' => 'bar'],
    'second' => ['bar' => 'baz'],
    1 => [2, 3]
])

$array->each(function($key, value) {
    // do some stuff with the key and value
})

each()方法返回相同的对象,因此您可以使用first()last()等所有方法进行链式调用。

如果您不想原地更改数组,可以使用all()方法与传统的foreach语句一起使用。以下是一个示例

$array = Ray::from([
    'first' => ['foo' => 'bar'],
    'second' => ['bar' => 'baz'],
    1 => [2, 3]
])

foreach($array->all() as $key => value) {
    // do some stuff with the key and value
}

访问键和值

您可以使用keys()values()方法访问数组的键和值

$array = Ray::from([
    'first' => ['foo' => 'bar'],
    'second' => ['bar' => 'baz'],
    1 => [2, 3]
])

$array->first()->keys(); // ['foo'];
$array->nth(2)->values(); // ['baz'];
$array->last()->keys(); // [0, 1];
$array->last()->values(); // [2, 3];