Array key prefix with string (:) in PHP

Fast; I know the solution, but I'm looking for something more elegant if it exists.

I am using PDO for new operators:

$sql = "INSERT INTO my_table (foo, bar, baz) VALUES (:foo, :bar, :baz)"; $source->execute($sql, array( ':foo' => $foo, ':bar' => $bar, ':baz' => $baz, )); 

This is fine, but I want to pass the previously created array, however, the keys contained in it are not a colon prefix ( : , and I believe that there should be an elegant way:

 $array = array( 'foo' => 'some', 'bar' => 'random', 'baz' => 'value', ); 

And translate it into:

 $array = array( ':foo' => 'some', ':bar' => 'random', ':baz' => 'value', ); 

Without execution:

 $temp = array(); foreach($array as $key => $value){ $temp[':' . $key] = $value; } $array = $temp; 

I looked through the PHP docs, but I cannot find a function (or sequence) that is suitable for this purpose.

Any ideas?


Adding

Leaving the accepted answer, but +1 @chim for his smart 1-liner; solves X in my XY problem. Reformed decision:

 $format = ':%s'; $values = array_flip(array_map(function ($key) use($format) { return sprintf($format, $key); }, array_flip($values))); 

Function completed, possibly array_keys_format(array $array, $format)

+6
source share
4 answers
 $source->execute($sql, array( 'foo' => $foo, 'bar' => $bar, 'baz' => $baz )); 

This implies the aforementioned calls to PDOStatement::execute() under the hood, the argument of which is the array above. 1

:)


1) Tested with versions 5.2.17 and 5.3.8 here and works as expected.
+8
source

This has already been answered, but this is what I came up with.

 $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); 
+3
source

use the map function php: 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); 
+2
source

One insert ...

 $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 is unsafe since array_flip relies on all unique values.

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

+2
source

Source: https://habr.com/ru/post/898431/


All Articles