Prefixing array keys with a string (:) in PHP

后端 未结 4 562
臣服心动
臣服心动 2021-01-18 10:56

Quick one; I know a solution, but I\'m looking for something more elegant if it exists.

I\'m using PDO for prepeared statements:

$sql = \"INSERT INTO         


        
相关标签:
4条回答
  • 2021-01-18 11:27
    $source->execute($sql, array(
        'foo' => $foo,
        'bar' => $bar,
        'baz' => $baz
    ));
    

    This is presuming the above calls PDOStatement::execute() under the hood, with the above array as its argument.1

    :)


    1) Tested with version 5.2.17 and 5.3.8 here, and working as expected.

    0 讨论(0)
  • 2021-01-18 11:33

    One liner...

    $array = array('test'=>'55','yest'=>'66');
    
    $array = array_flip(array_map(function($v){return ':' . $v;},array_flip($array)));
    
    // array(':test'=>'55',':yest'=>'66');
    

    However this isn't safe as array_flip relies on all values being unique.

    So one of the looping solutions is probably the best, or alternatively array_keys with array_combine.

    0 讨论(0)
  • 2021-01-18 11:40

    use the php map-function: http://php.net/manual/en/function.array-map.php

    function reduce($key)
    {
    if(strpos($key,":")===0)
    return substr($key,1);
    return $key;
    }
    
    $array = array_map("reduce",$array);
    
    0 讨论(0)
  • 2021-01-18 11:46

    It has already been answered but this is what I came up with anyway.

    $arr = array('foo'=>1,'bar'=>2);
    
    $arr = array_flip($arr);
    
    array_walk($arr,create_function('&$v,$k', '$v = ":$v";'));
    
    $arr = array_flip($arr);
    
    print_r($arr);
    
    0 讨论(0)
提交回复
热议问题