我正在尝试创建一个动态关联数组,但问题是它只保存最后一个键值对如何存储所有键值对?
foreach ($_POST as $var => $value) {
// Does the model have this attribute? If not raise an error
if ($model->hasAttribute($var))
$model->$var = $value;
elseif ($profile->hasAttribute($var)) {
$storage = array($var => $value);//associative array
} else {
//var_dump ($var);
$this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']));
}
}
答案 0 :(得分:0)
在您的代码中,您始终将$ storage分配给新阵列而不是附加它。(如果我错了,请纠正我。)
你应该以这种方式附加数组。
<?php
foreach ($_POST as $var => $value) {
// Does the model have this attribute? If not raise an error
if ($model->hasAttribute($var))
$model->$var = $value;
else if ($profile->hasAttribute($var)) {
if (!is_array($storage))
$storage = [];
$storage[$var] = $value; //associative array
} else {
//var_dump ($var);
$this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']));
}
}
答案 1 :(得分:0)
您好,您只有error
$storage = array($var => $value);//associative array
这一行每次创建一个新的array
$storage
,这就是为什么你只能获得最后key
value
对
试试这个
$storage = array();// initialize it as array
$storage[$var] = $value;// assign $value in $key index of $storage