[英]How to access and manipulate multi-dimensional array by key names / path?
我必須在 PHP 中實現一個設置器,它允許我指定數組(目標)的鍵或子鍵,將名稱作為點分隔鍵值傳遞。
給定以下代碼:
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
$key = 'b.x.z';
$path = explode('.', $key);
從$key
的值我想達到$arr['b']['x']['z']
的值5 。
現在,給定一個$key
的變量值和一個不同的$arr
值(具有不同的深度)。
$key
引用的元素的值? 對於getter get()
我寫了這段代碼:
public static function get($name, $default = null)
{
$setting_path = explode('.', $name);
$val = $this->settings;
foreach ($setting_path as $key) {
if(array_key_exists($key, $val)) {
$val = $val[$key];
} else {
$val = $default;
break;
}
}
return $val;
}
編寫setter更加困難,因為我成功地到達了正確的元素(來自$key
),但我無法在原始數組中設置值,而且我不知道如何一次指定所有鍵。
我應該使用某種回溯嗎? 或者我可以避免嗎?
假設$path
已經是一個通過explode
(或添加到函數)的數組,那么您可以使用引用。 如果$path
等無效,您需要添加一些錯誤檢查(想想isset
):
$key = 'b.x.z';
$path = explode('.', $key);
function get($path, $array) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
return $temp;
}
$value = get($path, $arr); //returns NULL if the path doesn't exist
如果您傳遞尚未定義的數組,則此組合將在現有數組中設置一個值或創建該數組。 確保將$array
定義$array
通過引用&$array
傳遞:
function set($path, &$array=array(), $value=null) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($path, $arr);
//or
set($path, $arr, 'some value');
這將unset
路徑中的最終鍵:
function unsetter($path, &$array) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
if(!is_array($temp[$key])) {
unset($temp[$key]);
} else {
$temp =& $temp[$key];
}
}
}
unsetter($path, $arr);
*原始答案有一些有限的功能,如果它們對某人有用,我會留下它們:
二傳手
確保將$array
定義$array
通過引用&$array
傳遞:
function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($arr, $path, 'some value');
或者,如果您想返回更新后的數組(因為我很無聊):
function set($array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
return $array;
}
$arr = set($arr, $path, 'some value');
創作者
如果您不想創建數組並選擇設置值:
function create($path, $value=null) {
//$path = explode('.', $path); //if needed
foreach(array_reverse($path) as $key) {
$value = array($key => $value);
}
return $value;
}
$arr = create($path);
//or
$arr = create($path, 'some value');
為了娛樂
在給定字符串bxz
構造和評估類似$array['b']['x']['z']
的bxz
:
function get($array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$result = \$array{$path};");
return $result;
}
設置類似$array['b']['x']['z'] = 'some value';
:
function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$array{$path} = $value;");
}
取消設置類似$array['b']['x']['z']
:
function unsetter(&$array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("unset(\$array{$path});");
}
我不是在純 PHP 中為您提供解決方案,而是使用ouzo 好東西具體使用Arrays::getNestedValue方法:
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
$key = 'b.x.z';
$path = explode('.', $key);
print_r(Arrays::getNestedValue($arr, $path));
同樣,如果您需要設置嵌套值,您可以使用Arrays::setNestedValue方法。
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
Arrays::setNestedValue($arr, array('d', 'e', 'f'), 'value');
print_r($arr);
我有一個我經常使用的實用程序,我將分享。 不同之處在於它使用數組訪問表示法(例如b[x][z]
)而不是點表示法(例如bxz
)。 通過文檔和代碼,它是相當不言自明的。
<?php
class Utils {
/**
* Gets the value from input based on path.
* Handles objects, arrays and scalars. Nesting can be mixed.
* E.g.: $input->a->b->c = 'val' or $input['a']['b']['c'] = 'val' will
* return "val" with path "a[b][c]".
* @see Utils::arrayParsePath
* @param mixed $input
* @param string $path
* @param mixed $default Optional default value to return on failure (null)
* @return NULL|mixed NULL on failure, or the value on success (which may also be NULL)
*/
public static function getValueByPath($input,$path,$default=null) {
if ( !(isset($input) && (static::isIterable($input) || is_scalar($input))) ) {
return $default; // null already or we can't deal with this, return early
}
$pathArray = static::arrayParsePath($path);
$last = &$input;
foreach ( $pathArray as $key ) {
if ( is_object($last) && property_exists($last,$key) ) {
$last = &$last->$key;
} else if ( (is_scalar($last) || is_array($last)) && isset($last[$key]) ) {
$last = &$last[$key];
} else {
return $default;
}
}
return $last;
}
/**
* Parses an array path like a[b][c] into a lookup array like array('a','b','c')
* @param string $path
* @return array
*/
public static function arrayParsePath($path) {
preg_match_all('/\\[([^[]*)]/',$path,$matches);
if ( isset($matches[1]) ) {
$matches = $matches[1];
} else {
$matches = array();
}
preg_match('/^([^[]+)/',$path,$name);
if ( isset($name[1]) ) {
array_unshift($matches,$name[1]);
} else {
$matches = array();
}
return $matches;
}
/**
* Check if a value/object/something is iterable/traversable,
* e.g. can it be run through a foreach?
* Tests for a scalar array (is_array), an instance of Traversable, and
* and instance of stdClass
* @param mixed $value
* @return boolean
*/
public static function isIterable($value) {
return is_array($value) || $value instanceof Traversable || $value instanceof stdClass;
}
}
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
$key = 'b[x][z]';
var_dump(Utils::getValueByPath($arr,$key)); // int 5
?>
作為“吸氣劑”,我過去曾使用過它:
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$key = 'data.one';
function find($key, $array) {
$parts = explode('.', $key);
foreach ($parts as $part) {
$array = $array[$part];
}
return $array;
}
$result = find($key, $array);
var_dump($result);
如果數組的鍵是唯一的,您可以使用array_walk_recursive在幾行代碼中解決問題:
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
function changeVal(&$v, $key, $mydata) {
if($key == $mydata[0]) {
$v = $mydata[1];
}
}
$key = 'z';
$value = '56';
array_walk_recursive($arr, 'changeVal', array($key, $value));
print_r($arr);
這是一種使用靜態類的方法。 這種風格的好處是您的配置將在您的應用程序中全局訪問。
它通過獲取一個關鍵路徑(例如“database.mysql.username”)並將字符串拆分為每個關鍵部分並移動指針以創建嵌套數組來工作。
這種方法的好處是您可以提供部分鍵並獲取配置值數組,而不僅限於最終值。 它還使“默認值”的實現變得微不足道。
如果您想擁有多個配置存儲,只需刪除靜態關鍵字並將其用作對象即可。
class Config
{
private static $configStore = [];
// This determines what separates the path
// Examples: "." = 'example.path.value' or "/" = 'example/path/value'
private static $separator = '.';
public static function set($key, $value)
{
$keys = explode(self::$separator, $key);
// Start at the root of the configuration array
$pointer = &self::$configStore;
foreach ($keys as $keySet) {
// Check to see if a key exists, if it doesn't, set that key as an empty array
if (!isset($pointer[$keySet])) {
$pointer[$keySet] = [];
}
// Set the pointer to the current key
$pointer = &$pointer[$keySet];
}
// Because we kept changing the pointer in the loop above, the pointer should be sitting at our desired location
$pointer = $value;
}
public static function get($key, $defaultValue = null)
{
$keys = explode(self::$separator, $key);
// Start at the root of the configuration array
$pointer = &self::$configStore;
foreach ($keys as $keySet) {
// If we don't have a key as a part of the path, we should return the default value (null)
if (!isset($pointer[$keySet])) {
return $defaultValue;
}
$pointer = &$pointer[$keySet];
}
// Because we kept changing the pointer in the loop above, the pointer should be sitting at our desired location
return $pointer;
}
}
// Examples of how to use
Config::set('database.mysql.username', 'exampleUsername');
Config::set('database.mysql.password', 'examplePassword');
Config::set('database.mysql.database', 'exampleDatabase');
Config::set('database.mysql.host', 'exampleHost');
// Get back all the database configuration keys
var_dump(Config::get('database.mysql'));
// Get back a particular key from the database configuration
var_dump(Config::get('database.mysql.host'));
// Get back a particular key from the database configuration with a default if it doesn't exist
var_dump(Config::get('database.mysql.port', 3306));
此函數與接受的答案相同,加上通過引用添加第三個參數,如果密鑰存在,則設置為 true/false
function drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
$ref = &$array;
foreach ($parents as $parent) {
if (is_array($ref) && array_key_exists($parent, $ref)) {
$ref = &$ref[$parent];
}
else {
$key_exists = FALSE;
$null = NULL;
return $null;
}
}
$key_exists = TRUE;
return $ref;
}
我對此有一個非常簡單和骯臟的解決方案(非常骯臟!如果密鑰的值不受信任,請勿使用!<\/strong> )。它可能比遍歷數組更有效。
function array_get($key, $array) {
return eval('return $array["' . str_replace('.', '"]["', $key) . '"];');
}
function array_set($key, &$array, $value=null) {
eval('$array["' . str_replace('.', '"]["', $key) . '"] = $value;');
}
getter
另一種解決方案,使用普通的array_reduce
方法
@AbraCadaver 的解決方案很好,但不完整:
['one' => 2]
'one.two'
類的標量值獲取鍵,則會引發錯誤我的解決方案是:
function get ($array, $path, $separator = '.') {
if (is_string($path)) {
$path = explode($separator, $path);
}
return array_reduce(
$path,
function ($carry, $item) {
return $carry[$item] ?? null;
},
$array
);
}
它需要 PHP 7,因為??
運算符,但這可以很容易地更改為舊版本...
這里有一個訪問和操作 MD 數組的簡單代碼。 但是沒有證券。
二傳手:
eval('$vars = &$array["' . implode('"]["', explode('.', strtolower($dot_seperator_path))) . '"];');
$vars = $new_value;
吸氣劑:
eval('$vars = $array["' . implode('"]["', explode('.', strtolower($dot_seperator_path))) . '"];');
return $vars;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.