114 lines
2.7 KiB
PHP
114 lines
2.7 KiB
PHP
<?php
|
|
namespace admin\components\UI\yii;
|
|
use Illuminate\Support\Enumerable;
|
|
|
|
/**
|
|
* Created by PhpStorm.
|
|
* User: chatfeed
|
|
* Date: 2022/5/18
|
|
* Time: 4:09 PM
|
|
*/
|
|
class Arr
|
|
{
|
|
public static function set(&$array, $key, $value)
|
|
{
|
|
if (is_null($key)) {
|
|
return $array = $value;
|
|
}
|
|
|
|
$keys = explode('.', $key);
|
|
|
|
foreach ($keys as $i => $key) {
|
|
if (count($keys) === 1) {
|
|
break;
|
|
}
|
|
|
|
unset($keys[$i]);
|
|
|
|
// If the key doesn't exist at this depth, we will just create an empty array
|
|
// to hold the next value, allowing us to create the arrays to hold final
|
|
// values at the correct depth. Then we'll keep digging into the array.
|
|
if (! isset($array[$key]) || ! is_array($array[$key])) {
|
|
$array[$key] = [];
|
|
}
|
|
|
|
$array = &$array[$key];
|
|
}
|
|
|
|
$array[array_shift($keys)] = $value;
|
|
|
|
return $array;
|
|
}
|
|
|
|
public static function has($array, $keys)
|
|
{
|
|
$keys = (array) $keys;
|
|
|
|
if (! $array || $keys === []) {
|
|
return false;
|
|
}
|
|
|
|
foreach ($keys as $key) {
|
|
$subKeyArray = $array;
|
|
|
|
if (static::exists($array, $key)) {
|
|
continue;
|
|
}
|
|
|
|
foreach (explode('.', $key) as $segment) {
|
|
if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) {
|
|
$subKeyArray = $subKeyArray[$segment];
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
public static function get($array, $key, $default = null)
|
|
{
|
|
if (! static::accessible($array)) {
|
|
return value($default);
|
|
}
|
|
|
|
if (is_null($key)) {
|
|
return $array;
|
|
}
|
|
|
|
if (static::exists($array, $key)) {
|
|
return $array[$key];
|
|
}
|
|
|
|
if (strpos($key, '.') === false) {
|
|
return $array[$key] ?? value($default);
|
|
}
|
|
|
|
foreach (explode('.', $key) as $segment) {
|
|
if (static::accessible($array) && static::exists($array, $segment)) {
|
|
$array = $array[$segment];
|
|
} else {
|
|
return value($default);
|
|
}
|
|
}
|
|
|
|
return $array;
|
|
}
|
|
public static function accessible($value)
|
|
{
|
|
return is_array($value) || $value instanceof \ArrayAccess;
|
|
}
|
|
public static function exists($array, $key)
|
|
{
|
|
if ($array instanceof Enumerable) {
|
|
return $array->has($key);
|
|
}
|
|
|
|
if ($array instanceof \ArrayAccess) {
|
|
return $array->offsetExists($key);
|
|
}
|
|
|
|
return array_key_exists($key, $array);
|
|
}
|
|
}
|