duanjing1023 2011-09-30 22:08
浏览 40
已采纳

通过引用传递密钥和值的替代方法:

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?

  • 写回答

2条回答 默认 最新

  • douxi2011 2011-09-30 22:49
    关注

    Can someone explain to me why you can't pass a key as reference?

    Because the language does not support this. You'd be hard-pressed to find this ability in most languages, hence the term key.

    So am I stuck with something like this?

    Yes. The best way is to create a new array with the appropriate keys.

    Any alternatives?

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题