我要在PHP中实现 setter ,它允许我指定数组(目标)的键或子键,将名称作为点分隔键传递值。
给出以下代码:
$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
),但是我无法在原始数组中设置值而我不知道如何一次指定所有键。
我应该使用某种回溯吗?或者我能避免吗?
答案 0 :(得分:22)
假设$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
:
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
:
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');
乐趣
在给定字符串$array['b']['x']['z'];
:
b.x.z
之类的内容
function get($array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$result = \$array{$path};");
return $result;
}
答案 1 :(得分:4)
我的解决方案不是纯PHP,而是使用ouzo goodies具体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);
答案 2 :(得分:1)
我有一个我经常使用的实用程序,我将分享。不同之处在于它使用数组访问表示法(例如b[x][z]
)而不是点表示法(例如b.x.z
)。使用文档和代码,它是相当不言自明的。
<?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
?>
答案 3 :(得分:1)
如果数组的键是唯一的,您可以使用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);
答案 4 :(得分:1)
这是使用静态类的方法。这种样式的好处是您的配置将可以在应用程序中全局访问。
它的工作方式是输入一个关键路径,例如“ database.mysql.username”,并将字符串拆分为每个关键部分,然后移动指针以创建嵌套数组。
这种方法的好处是您可以提供部分键并获取配置值的数组,而不仅限于最终值。这也使“默认值”的实现很容易。
如果您想拥有多个配置存储,只需删除static关键字并将其用作对象即可。
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));
答案 5 :(得分:0)
作为一个“吸气者”,我过去曾经使用过这个:
$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);
答案 6 :(得分:0)
此函数与接受的答案相同,另外通过引用添加第三个参数,如果键存在则设置为true / false
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<center>
<h3 id="h3A"> </h3>
<h4> vs </h4>
<h3 id="h3B"> </h3>
<h4> 60 - 70 </h4>
</center>
<div class="12u$">
<div class="select-wrapper">
<select name="teamA" id="teamA" style="max-width:30%;">
<option value="">- TeamA -</option>
<option value="1">Kansas</option>
<option value="1">Oklahoma</option>
<option value=4>Texas</option>
<option value="1">Notre Dame</option>
</select>
</div>
</div>
<div class="12u$">
<div class="select-wrapper">
<select name="teamB" id="teamB" style="max-width:30%;">
<option value="">- TeamB -</option>
<option value="1">Kansas</option>
<option value="1">Oklahoma</option>
<option value="1">Texas</option>
<option value="1">Notre Dame</option>
</select>
</div>
</div>
$("#teamA")
.change(function() {
var str = "";
$("select option:selected").each(function() {
str = $(this).text() + " "; // var of what im changing
});
$("#h3A").text(str); // target of what to change
})
.change(); // make it happen
$("#teamB")
.change(function() {
var str = "";
$("select option:selected").each(function() {
str = $(this).text() + " "; // var of what im changing
});
$("#h3B").text(str); // target of what to change
})
.change(); // make it happen
答案 7 :(得分:0)
我有一个非常简单和肮脏的解决方案(非常脏!如果密钥的值不受信任,请不要使用!)。它可能比循环遍历数组更有效。
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;');
}
这两个函数都在一段代码上执行eval
,其中密钥作为PHP代码转换为数组元素。它返回或设置相应键的数组值。
答案 8 :(得分:0)
使用普通的getter
方法为array_reduce
提供另一种解决方案
@AbraCadaver的解决方案不错,但还不完整:
'one.two'
中的['one' => 2]
之类的标量值中获取密钥,则会引发错误我的解决方法是:
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,但是对于较早的版本,可以很容易地更改它...
答案 9 :(得分:-1)
下面是访问和操作MD数组的简单代码。但是没有证券。
设置者:
eval('$vars = &$array["' . implode('"]["', explode('.', strtolower($dot_seperator_path))) . '"];');
$vars = $new_value;
获取器:
eval('$vars = $array["' . implode('"]["', explode('.', strtolower($dot_seperator_path))) . '"];');
return $vars;