Php 如何在Yii2中为数组值生成活动隐藏输入

Php 如何在Yii2中为数组值生成活动隐藏输入,php,yii2,Php,Yii2,我有一个表单属性的多维数组值,我需要将它作为隐藏输入包含在表单中 $model->ids = ['first' => [1, 2], 'second' => [22]]; 我不能使用activeHiddenInput,因为它会产生错误 // gives error: "Array to string conversion" <?= Html::activeHiddenInput($model, 'ids')?> //给出错误:“数组到字符串的转换” 预期成果:

我有一个表单属性的多维数组值,我需要将它作为隐藏输入包含在表单中

$model->ids = ['first' => [1, 2], 'second' => [22]];
我不能使用activeHiddenInput,因为它会产生错误

// gives error: "Array to string conversion"
<?= Html::activeHiddenInput($model, 'ids')?>
//给出错误:“数组到字符串的转换”
预期成果:

<input type="hidden" name="formName[ids][first][]" value="1" />
<input type="hidden" name="formName[ids][first][]" value="2" />
<input type="hidden" name="formName[ids][second][]" value="22" />

。。或者

<input type="hidden" name="formName[ids][first][0]" value="1" />
<input type="hidden" name="formName[ids][first][1]" value="2" />
<input type="hidden" name="formName[ids][second][0]" value="22" />


在Yi2框架概念中,解决这一问题的最佳方法是什么?

因此,如果有人需要,我就是这样解决的

我使用以下方法扩展了
yii/bootstrap/Html
类:

/**
 * Generates list of hidden input tags for the given model attribute when the attribute's value is an array.
 *
 * @param Model $model
 * @param string $attribute
 * @param array $options
 * @return string
 */
public static function activeHiddenInputList($model, $attribute, $options = [])
{
    $str = '';
    $flattenedList = static::getflatInputNames($attribute, $model->$attribute);
    foreach ($flattenedList as $flattenAttribute) {
        $str.= static::activeHiddenInput($model, $flattenAttribute, $options);
    }
    return $str;
}

/**
 * @param string $name
 * @param array $values
 * @return array
 */
private static function getflatInputNames($name, array $values)
{
    $flattened = [];
    foreach ($values as $key => $val) {
        $nameWithKey = $name . '[' . $key . ']';
        if (is_array($val)) {
            $flattened += static::getflatInputNames($nameWithKey, $val);
        } else {
            $flattened[] = $nameWithKey;
        }
    }
    return $flattened;
}
调用
Html::activeHiddenInputList($model,'ids')将给出

<input id="formname-ids-first-0" type="hidden" name="formName[ids][first][0]" value="1" />
<input id="formname-ids-first-1" type="hidden" name="formName[ids][first][1]" value="2" />
<input id="formname-ids-second-0" type="hidden" name="formName[ids][second][0]" value="22" />


在现场循环我正在寻找适用于任何深度阵列的良好通用解决方案。目前它需要2个嵌套for循环,但是如果深度为3,4呢?编写一个递归函数,而不是如果深度未知/不受限制,则需要使用递归函数。但yii2概念中有好的解决方案吗?为了便于使用,该功能应该放在哪里?Yi2提供的任何工具都可以使其更可读、更简单吗?