How to access and manipulate multi-dimensional array by key names / path?

前端 未结 10 2197
北恋
北恋 2020-11-21 07:35

I\'ve to implement a setter in PHP, that allows me to specify the key, or sub key, of an array (the target), passing the name as a dot-separated-keys value.

10条回答
  •  终归单人心
    2020-11-21 07:46

    This function does the same as the accepted answer, plus is adds a third parameter by reference that is set to true/false if the key is present

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

提交回复
热议问题