简体   繁体   English

PHP数组,在foreach循环中替换键

[英]PHP array, substitute the key within a foreach loop

I have read a lot of posts and have not been able to find a solution to my issue. 我已经阅读了很多文章,却找不到解决我问题的方法。

I have a $_POST array named "Water", $_POST['Water'] and its contents are: 我有一个名为“ Water”的$_POST数组, $_POST['Water'] ,其内容为:

 [Water] => Array ( [0] => 55.0 [1] => 22 )

Is it possible to use the name of the post inside a foreach loop so the $key could use the name "Water": 是否可以在foreach循环中使用帖子的名称,以便$key可以使用名称“ Water”:

foreach($_POST['Water']  as $key => $val) {
    $fields[] = "$field = '$val'";
    //echo "Key: $key, Value: $val<br/>\n";
}

Many thanks for your time. 非常感谢您的宝贵时间。

Not really. 并不是的。 foreach() operates on the contents of an array. foreach()对数组的内容进行操作。 Whatever actually contains that array is outside of foreach's view. 实际包含该数组的内容不在foreach的视野范围内。 If you want to dynamically use the Water key elsewhere, you'll have to do that yourself: 如果要在其他地方动态使用Water键,则必须自己执行以下操作:

$key = 'Water'
foreach($_POST[$key] as $val) {
   $fields[] = "$key = '$val'";
}

If I read this right you basically want $field='water' inside the foreach . 如果我没看错的话,你基本上想在foreach里面放$field='water' This can be done be rethinking the way we build the foreach . 可以通过重新思考构建foreach的方式来做到这一点。

You simply need to make the field value a variable and pass use that rather everywhere the value is needed. 您只需要使字段值成为变量,然后在需要该值的任何地方使用它即可。

$field = 'Water';
foreach($_POST[$field]  as $key => $val) {
    $fields[] = "$field = '$val'";
    //echo "Key: $key, Value: $val<br/>\n";
}

The advantage of this approach is that if you change your mind and the $_POST key is later called, "liquid" one single line needs to be edited and that is all. 这种方法的优点是,如果您改变主意,后来又调用$ _POST键,则“液态”一行需要编辑,仅此而已。 Furthermore, if your foreach were part of a function $field could be a function parameter. 此外,如果您的foreach是函数的一部分,则$ field可以是函数参数。 In a roundabout way, you are actually getting pretty close to some code reuse principles. 实际上,您实际上已经接近一些代码重用原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM