PHP foreach 更改原始数组值 [英] PHP foreach change original array values
问题描述
我对多维数组很陌生,这让我很烦恼.
I am very new in multi dimensional arrays, and this is bugging me big time.
我的数组如下:
$fields = array(
"names" => array(
"type" => "text",
"class" => "name",
"name" => "name",
"text_before" => "name",
"value" => "",
"required" => true,
)
)
然后我得到了一个函数来检查这些输入是否被填写,如果它们是必需的.
Then i got a function checking if these inputs are filled in, if they are required.
function checkForm($fields){
foreach($fields as $field){
if($field['required'] && strlen($_POST[$field['name']]) <= 0){
$fields[$field]['value'] = "Some error";
}
}
return $fields;
}
现在我的问题是这条线
$fields[$field]['value'] = "Some error";
我想更改原始数组的内容,因为我要返回它,但是如何在我的 foreach 循环中获取当前数组的名称(在此示例中为名称)?
I want to change the content of the original array, since i am returning this, but how do I get the name of the current array (names in this example) in my foreach loop?
推荐答案
在 PHP 中,通过引用传递 (&
) 是......有争议的.我建议不要使用它,除非您知道为什么需要它并测试结果.
In PHP, passing by reference (&
) is ... controversial. I recommend not using it unless you know why you need it and test the results.
我建议您执行以下操作:
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
所以基本上在需要值时使用 $field
,在需要更改数据时使用 $fields[$key]
.
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
这篇关于PHP foreach 更改原始数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!