mirror of
https://devops.lemonos.cn/lawson/FendxPHP.git
synced 2026-06-15 23:12:49 +08:00
64 lines
1.6 KiB
PHP
64 lines
1.6 KiB
PHP
|
|
<?php
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace Fendx\Common\Util;
|
||
|
|
|
||
|
|
class ArrayHelper
|
||
|
|
{
|
||
|
|
public static function get(array $array, string $key, mixed $default = null): mixed
|
||
|
|
{
|
||
|
|
if ($key === '') {
|
||
|
|
return $default;
|
||
|
|
}
|
||
|
|
|
||
|
|
$keys = explode('.', $key);
|
||
|
|
$value = $array;
|
||
|
|
|
||
|
|
foreach ($keys as $k) {
|
||
|
|
if (!is_array($value) || !array_key_exists($k, $value)) {
|
||
|
|
return $default;
|
||
|
|
}
|
||
|
|
$value = $value[$k];
|
||
|
|
}
|
||
|
|
|
||
|
|
return $value;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function set(array &$array, string $key, mixed $value): void
|
||
|
|
{
|
||
|
|
$keys = explode('.', $key);
|
||
|
|
$current = &$array;
|
||
|
|
|
||
|
|
foreach ($keys as $k) {
|
||
|
|
if (!is_array($current)) {
|
||
|
|
$current = [];
|
||
|
|
}
|
||
|
|
if (!array_key_exists($k, $current)) {
|
||
|
|
$current[$k] = [];
|
||
|
|
}
|
||
|
|
$current = &$current[$k];
|
||
|
|
}
|
||
|
|
|
||
|
|
$current = $value;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function merge(array ...$arrays): array
|
||
|
|
{
|
||
|
|
$result = [];
|
||
|
|
|
||
|
|
foreach ($arrays as $array) {
|
||
|
|
foreach ($array as $key => $value) {
|
||
|
|
if (is_int($key)) {
|
||
|
|
$result[] = $value;
|
||
|
|
} elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
|
||
|
|
$result[$key] = self::merge($result[$key], $value);
|
||
|
|
} else {
|
||
|
|
$result[$key] = $value;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
}
|