dot()
dot( $array, string $prepend = '') : array
使用”.”号将将多维数组转化为一维数组
Parameters
$array | ||
string | $prepend |
<?php
namespace ticky\helper;
class arr {
/**
* 使用”.”号将将多维数组转化为一维数组
* @param $array
* @param string $prepend
* @return array
*/
public static function dot($array, $prepend = '') {
$results = [];
foreach ($array as $key => $value) {
if (is_array($value) && !empty($value)) {
$results = array_merge($results, static::dot($value, $prepend . $key . '.'));
} else {
$results[$prepend . $key] = $value;
}
}
return $results;
}
/**
* 使用”.”号从嵌套数组中移除给定键值对
* @param $array
* @param $keys
*/
public static function forget(&$array, $keys) {
$original = &$array;
$keys = (array) $keys;
if (count($keys) === 0) {
return;
}
foreach ($keys as $key) {
// if the exact key exists in the top-level, remove it
if (static::exists($array, $key)) {
unset($array[$key]);
continue;
}
$parts = explode('.', $key);
// clean up before each pass
$array = &$original;
while (count($parts) > 1) {
$part = array_shift($parts);
if (isset($array[$part]) && is_array($array[$part])) {
$array = &$array[$part];
} else {
continue 2;
}
}
unset($array[array_shift($parts)]);
}
}
public static function exists($array, $key) {
if ($array instanceof \ArrayAccess) {
return $array->offsetExists($key);
}
return array_key_exists($key, $array);
}
}