Last active
October 7, 2022 07:54
-
-
Save dakatsuka/5263319 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Store | |
{ | |
public static $data = []; | |
public static function set() | |
{ | |
$params = static::parseArguments(func_get_args()); | |
static::$data = static::merge(static::$data, $params); | |
} | |
private static function parseArguments($args) | |
{ | |
$result = []; | |
$key = array_shift($args); | |
if (count($args) === 1) { | |
$result[$key] = $args[0]; | |
} else { | |
$result[$key] = static::parseArguments($args); | |
} | |
return $result; | |
} | |
private static function merge($array1, $array2) | |
{ | |
foreach ($array2 as $key => $value) { | |
if (!is_array($array1)) { | |
$array1 = [$array1]; | |
} | |
if (is_array($value)) { | |
if (!isset($array1[$key])) { | |
$array1[$key] = []; | |
} | |
$array1[$key] = static::merge($array1[$key], $value); | |
} else { | |
$array1[$key] = $value; | |
} | |
} | |
return $array1; | |
} | |
} | |
Store::set('user', 'profile', 'email', 'example@example.com'); | |
Store::set('user', 'profile', 'nickname', 'dakatsuka'); | |
Store::set('hoge', 'fuga'); | |
print_r(Store::$data); | |
/** | |
Array | |
( | |
[user] => Array | |
( | |
[profile] => Array | |
( | |
[email] => example@example.com | |
[nickname] => dakatsuka | |
) | |
) | |
[hoge] => fuga | |
) | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment