通过引用传递键和值的替代方法:
有人可以向我解释为什么你不能传递密钥作为参考吗?
例如:
if(is_array($where)){
foreach($where as &$key => &$value){
$key = sec($key);
$value = sec($value);
}
unset($key, $value);
}
抛出:
Fatal error: Key element cannot be a reference in linkstest.php on line 2
我可以使用 array_map 做类似的事情吗? 我想做的就是迭代关联数组,并使用 sec() 函数转义键和值。
数组映射对我来说很难理解:
我已经用 array_map 尝试了很多东西,但我无法让它直接作用于按键。
使用数组映射比仅使用 foreach 循环可以获得任何性能优势吗?
我不喜欢 foreach 的是,我不能直接对数组进行操作,并且必须处理创建临时数组并取消设置它们:
foreach($where as $key => $value){
$where[secure($key)] = secure($value);
}
如果它在键中找到需要转义的内容,添加一个新元素,这可能会失败,并保留未转义的一个。
那么我是否陷入了这样的困境?
$temparr = array();
foreach($where as $key => $value){
$temparr[secure($key)] = secure($value);
}
$where = $temparr;
unset($temparr);
还有其他选择吗?
Can someone explain to me why you can't pass a key as reference?
Ex:
if(is_array($where)){
foreach($where as &$key => &$value){
$key = sec($key);
$value = sec($value);
}
unset($key, $value);
}
Throws:
Fatal error: Key element cannot be a reference in linkstest.php on line 2
Can I do something similar using array_map?
All I want to do is iterate over an associative array, and escape both the key and value with my sec() function.
Array map is difficult for me to understand:
I have tried many things with array_map, but I can't get it to act on the keys directly.
Would I get any performance benefit using array map than just using a foreach loop?
What I don't like about foreach is that I can't act on the array directly, and have to deal with creating temporary arrays and unsetting them:
foreach($where as $key => $value){
$where[secure($key)] = secure($value);
}
This might fail if it finds something to escape in the key, adding a new element, and keeping the unescaped one.
So am I stuck with something like this?
$temparr = array();
foreach($where as $key => $value){
$temparr[secure($key)] = secure($value);
}
$where = $temparr;
unset($temparr);
Any alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为语言不支持这个。在大多数语言中你很难找到这种能力,因此有了术语key。
是的。最好的方法是使用适当的键创建一个新数组。
提供更好替代方案的唯一方法是了解您的具体情况。如果您的键映射到表列名称,那么最好的方法是保留键原样,并在 SQL 中使用它们时对其进行转义。
Because the language does not support this. You'd be hard-pressed to find this ability in most languages, hence the term key.
Yes. The best way is to create a new array with the appropriate keys.
The only way to provide better alternatives is to know your specific situation. If your keys map to table column names, then the best approach is to leave the keys as is and escape them at their time of use in your SQL.
为什么这样做有问题?让它成为一个函数。函数接受输入并给出输出。您的函数输入将是您的“不安全”数组。您的输出将是保护阵列的结果。
然后你就这样做
这就是为什么你有能力制作函数......
why is it a problem to do that? Make it a function. A function takes an input and gives an output. Your function input will be your "unsecured" array. Your output will be the result of securing the array.
Then you just do
That's why you have the ability to make functions...