从索引数组中获取多维数组的最佳方法[重复]


Moso31
2025-02-24 06:57:56 (25天前)


假设我有一个字符串a.b.c.d.e,我将它爆炸。我得到一个[a,b,c,d,e]数组。我想从中构建一个多维数组,每个字母代表一个“维度”。

我想要的是……

6 条回复
  1. 0# 回忆氵独奏♪ | 2019-08-31 10-32



    此函数与接受的答案相同,另外通过引用添加第三个参数,如果密钥存在,则设置为true / false




    1. 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;
      }

    2. </code>

  2. 1# v-star*위위 | 2019-08-31 10-32



    我有一个我经常使用的实用程序,我会分享。不同之处在于它使用数组访问符号(例如

    b[x][z]

    )而不是点符号(例如

    b.x.z

    )。使用文档和代码,它是相当不言自明的。




    1. <?php
      class Utils {
      /**

    2.  * Gets the value from input based on path.
    3.  * Handles objects, arrays and scalars. Nesting can be mixed.
    4.  * E.g.: $input->a->b->c = 'val' or $input['a']['b']['c'] = 'val' will
    5.  * return "val" with path "a[b][c]".
    6.  * @see Utils::arrayParsePath
    7.  * @param mixed $input
    8.  * @param string $path
    9.  * @param mixed $default Optional default value to return on failure (null)
    10.  * @return NULL|mixed NULL on failure, or the value on success (which may also be NULL)
    11.  */
    12. public static function getValueByPath($input,$path,$default=null) {
    13.     if ( !(isset($input) && (static::isIterable($input) || is_scalar($input))) ) {
    14.         return $default; // null already or we can't deal with this, return early
    15.     }
    16.     $pathArray = static::arrayParsePath($path);
    17.     $last = &$input;
    18.     foreach ( $pathArray as $key ) {
    19.         if ( is_object($last) && property_exists($last,$key) ) {
    20.             $last = &$last->$key;
    21.         } else if ( (is_scalar($last) || is_array($last)) && isset($last[$key]) ) {
    22.             $last = &$last[$key];
    23.         } else {
    24.             return $default;
    25.         }
    26.     }
    27.     return $last;
    28. }
    29. /**
    30.  * Parses an array path like a[b][c] into a lookup array like array('a','b','c')
    31.  * @param string $path
    32.  * @return array
    33.  */
    34. public static function arrayParsePath($path) {
    35.     preg_match_all('/\\[([^[]*)]/',$path,$matches);
    36.     if ( isset($matches[1]) ) {
    37.         $matches = $matches[1];
    38.     } else {
    39.         $matches = array();
    40.     }
    41.     preg_match('/^([^[]+)/',$path,$name);
    42.     if ( isset($name[1]) ) {
    43.         array_unshift($matches,$name[1]);
    44.     } else {
    45.         $matches = array();
    46.     }
    47.     return $matches;
    48. }
    49. /**
    50.  * Check if a value/object/something is iterable/traversable, 
    51.  * e.g. can it be run through a foreach? 
    52.  * Tests for a scalar array (is_array), an instance of Traversable, and 
    53.  * and instance of stdClass
    54.  * @param mixed $value
    55.  * @return boolean
    56.  */
    57. public static function isIterable($value) {
    58.     return is_array($value) || $value instanceof Traversable || $value instanceof stdClass;
    59. }
    60. }

    61. $arr = array(‘a => 1,
      b => array(
      y => 2,
      x => array(‘z => 5, w => abc’)
      ),
      c => null);

    62. $key = b[x][z]’;

    63. var_dump(Utils::getValueByPath($arr,$key)); // int 5

    64. ?>

    65. </code>

  3. 2# 甲基蓝 | 2019-08-31 10-32



    作为一个“吸气者”,我过去曾用过这个:




    1. $array = array(‘data => array(‘one => first’, two => second’));

    2. $key = data.one’;

    3. function find($key, $array) {
      $parts = explode(‘.’, $key);
      foreach ($parts as $part) {
      $array = $array[$part];
      }
      return $array;
      }

    4. $result = find($key, $array);
      var_dump($result);

    5. </code>

  4. 3# 哇。 | 2019-08-31 10-32



    我有一个非常简单和肮脏的解决方案(

    真脏!如果密钥的值不受信任,请勿使用!
    </强>
    )。它可能比循环遍历数组更有效。




    1. function array_get($key, $array) {
      return eval(‘return $array[“‘ . str_replace(‘.’, ‘“][“‘, $key) . ‘“];’);
      }

    2. function array_set($key, &$array, $value=null) {
      eval(‘$array[“‘ . str_replace(‘.’, ‘“][“‘, $key) . ‘“] = $value;’);
      }

    3. </code>


    这两个功能都有


    eval


    在一段代码中,密钥作为PHP代码转换为数组的元素。它返回或设置相应键的数组值。


  5. 4# 庸人自扰 | 2019-08-31 10-32



    如果数组的键是唯一的,您可以使用几行代码解决问题

    array_walk_recursive





    1. $arr = array(‘a => 1,
      b => array(
      y => 2,
      x => array(‘z => 5, w => abc’)
      ),
      c => null);

    2. function changeVal(&$v, $key, $mydata) {
    3.     if($key == $mydata[0]) {
    4.         $v = $mydata[1];
    5.     }
    6. }
    7. $key = 'z';
    8. $value = '56';
    9. array_walk_recursive($arr, 'changeVal', array($key, $value));
    10. print_r($arr);
    11. </code>

登录 后才能参与评论