不使用递归函数和/或循环访问多维数组值


Accessing Multidimensional Array Values without recursive functions and/or loops

我有索引ponter,例如5-1-key2-3

我的array有它的address:

array(
  '5'=>array(
     '1'=>array(
        'key2'=>array(
             '3'=>'here it is - 5-1-key2-3 key address'
         )
      )
   )
)

等于

$arr[5][1][key2][3]='here it is - 5-1-key2-3 key address';

我知道我可以构建递归函数来访问这个值。

但是我很好奇是否可以在没有递归和构建用户函数和/或循环的情况下实现这一点。

可能可以在php中使用variable variables功能。

您可以使用以下代码

$keys = explode('-', '5-1-key2-3');
// start from the root of the array and progress through the elements
$temp = $arr;
foreach ($keys as $key_value)
{
    $temp = $temp[$key_value];
}
// this will give you $arr["5"]["1"]["key2"]["3"] element value
echo $temp;

修改后,我得到了更好的理解的问题,我认为你可以做eval:

<?php
function getArrValuesFromString($string, $arr) {
  $stringArr = '$arr[''' . str_replace('-', "']['", $string) . ''']';
  eval("'$t = " . $stringArr . ";");
  return $t;
}
$arr[5][1]['key2'][3] = '1here it is - 5-1-key2-3 key address';
$string = '5-1-key2-3';
echo getArrValuesFromString($string, $arr); //1here it is - 5-1-key2-3 key address

EDIT:

出于安全考虑,我非常不赞成这种方式,但如果你确定自己在做什么:

$key = 'a-b-c-d';
$array = <<your array>>;
$keys = explode('-', $key);
// we can surely do something better like checking for each one if its a string or int then adding or not the `'`
$final_key = "['".implode("']['", $keys)."']";
$result = eval("return '$array{$final_key};");

我写了一门课,灵感来自我在网上看到的东西,不记得在哪里了,但无论如何,这可以帮助你:

/**
 * Class MultidimensionalHelper
 *
 * Some help about multidimensional arrays
 * like dynamic array_key_exists, set, and get functions
 *
 * @package Core'Utils'Arrays
 */
class MultidimensionalHelper
{
    protected $keySeparator = '.';
    /**
     * @return string
     */
    public function keySeparator()
    {
        return $this->keySeparator;
    }
    /**
     * @param string $keySeparator
     */
    public function setKeySeparator($keySeparator)
    {
        $this->keySeparator = $keySeparator;
    }

    /**
     * Multidimensional array dynamic array_key_exists
     *
     * @param $key      String Needle
     * @param $array    Array  Haystack
     * @return bool     True if found, false either
     */
    public function exists($key, $array)
    {
        $keys = explode($this->keySeparator(), $key);
        $tmp = $array;
        foreach($keys as $k)
        {
            if(!array_key_exists($k, $tmp))
            {
                return false;
            }
            $tmp = $tmp[$k];
        }
        return true;
    }
    /**
     * Multidimensional array dynamic getter
     *
     *
     * @param $key      String  Needle
     * @param $array    Array   Haystack
     * @return mixed    Null if key not exists or the content of the key
     */
    public function get($key, $array)
    {
        $keys = explode($this->keySeparator(), $key);
        $lkey = array_pop($keys);
        $tmp = $array;
        foreach($keys as $k)
        {
            if(!isset($tmp[$k]))
            {
                return null;
            }
            $tmp = $tmp[$k];
        }
        return $tmp[$lkey];
    }
    /**
     * Multidimensional array dynamic setter
     *
     * @param String    $key
     * @param Mixed     $value
     * @param Array     $array  Array to modify
     * @param Bool      $return
     * @return Array    If $return is set to TRUE (bool), this function
     *                  returns the modified array instead of directly modifying it.
     */
    public function set($key, $value, &$array)
    {
        $keys = explode($this->keySeparator(), $key);
        $lkey = array_pop($keys);
        $tmp = &$array;
        foreach($keys as $k)
        {
            if(!isset($tmp[$k]) || !is_array($tmp[$k]))
            {
                $tmp[$k] = array();
            }
            $tmp = &$tmp[$k];
        }
        $tmp[$lkey] = $value;
        unset($tmp);
    }
}

然后使用:

$MDH = new MultidimensionalHelper();
$MDH->setKeySeparator('-');
$arr = [ 
    'a' => [
        'b' => [
            'c' => 'good value',
        ],
        'c' => 'wrong value',
    ],
    'b' => [
        'c' => 'wrong value',
    ]
];
$key = 'a-b-c';
$val = $MDH->get($key, $arr);
var_dump($val);

如果你在类代码中没有找到get函数的内容,下面是它的内容:

public function get($key, $array)
{
    $keys = explode($this->keySeparator(), $key);
    $lkey = array_pop($keys);
    $tmp = $array;
    foreach($keys as $k)
    {
        if(!isset($tmp[$k]))
        {
            return null;
        }
        $tmp = $tmp[$k];
    }
    return $tmp[$lkey];
}