我有这个数组
$arr = ['field_event_start_date', 'widget', 0, 'value', '#date_part_order', 3]
我想将其转换为以下格式的数组
$form['field_event_start_date']['widget'][0]['value']['#date_part_order'][3]
尝试将数组追加到$form
数组。
我有一个$form
数组,其中包含许多字段,并且我想取消设置一组字段。上面的数组是更大数组的一部分。如果我使用此数组,如何将其转换为如下所示的数组
$form['field_event_start_date']['widget'][0]['value']['#date_part_order'][3]
我已经尝试过,这样内爆,$form[implode('][', $arr)]
但这总是说,未定义的索引。
我需要运行的最终代码是
unset($form['field_event_start_date']['widget'][0]['value']['#date_part_order'][3]);
但是,有许多类似这样的方法,其深度数是变化的。我需要编写一个通用函数来实现此目的。
在Drupal 8中,您可以NestedArray::unsetValue()
用来取消设置嵌套数组的值。您还可以使用NestedArray::getValue()
和NestedArray::setValue()
通过键数组($parents
)从嵌套数组中获取和设置值。
Drupal 7只有drupal_array_get_nested_value()
和drupal_array_set_nested_value()
。但是没有drupal_array_unset_nested_value()
。它可以很容易地从Drupal 8移植:
/**
* Unsets a value in a nested array with variable depth.
*
* This helper function should be used when the depth of the array element you
* are changing may vary (that is, the number of parent keys is variable). It
* is primarily used for form structures and renderable arrays.
*
* @param array $array
* A reference to the array to modify.
* @param array $parents
* An array of parent keys, starting with the outermost key and including
* the key to be unset.
* @param bool $key_existed
* (optional) If given, an already defined variable that is altered by
* reference.
*
* Port of NestedArray::unsetValue() from Drupal 8
*
* @see drupal_array_get_nested_value()
* @see drupal_array_set_nested_value()
*/
function drupal_array_unset_nested_value(array &$array, array $parents, &$key_existed = NULL) {
$unset_key = array_pop($parents);
$ref = &drupal_array_get_nested_value($array, $parents, $key_existed);
if ($key_existed && is_array($ref) && array_key_exists($unset_key, $ref)) {
$key_existed = TRUE;
unset($ref[$unset_key]);
}
else {
$key_existed = FALSE;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句