用字符串prefixing数组键(:)在PHP

编程入门 行业动态 更新时间:2024-10-27 16:39:40
本文介绍了用字符串prefixing数组键(:)在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

快速之一;我知道一个解决方案,但我在寻找,如果它存在的东西更优雅。

我使用的是PDO为prepeared语句:

$ SQL =INSERT INTO my_table的(富,酒吧,巴兹)VALUES(:foo,那么:酒吧,:巴兹);$源 - >执行($ sql中,数组(    ':富'=> $ foo的,    ':酒吧'=> $吧,    ':巴兹'=> $巴兹,));

这是好的,但我想在pviously创造了$ P $阵传球,但是包含的键是不是由冒号( pfixed $ P $: ),我算起来也必须采取一种优雅的方式:

$阵列=阵列(    '富'=> '一些',    '酒吧'=> '随机',    巴兹'=> '值',);

和它翻译成:

$阵列=阵列(    ':富'=> '一些',    ':酒吧'=> '随机',    ':巴兹'=> '值',);

如果没有这样做的:

$ TEMP =阵列();的foreach($数组$关键=> $值){    $温度[':'。 $关键] = $价值;}$阵列= $温度;

我浏览过的PHP文件,但我不能找到一个函数(或序列的)适合的目的。

任何想法?

附录

留下接受的答案,但+1 @chim他的聪明1衬板;解决了我的问题XY在X。格式化的解决方案:

$格式=':%s'的;$值= array_flip(array_map(函数($键)使用($格式){    返回的sprintf($格式,$键);},array_flip($值)));

裹功能,也许 array_keys_format(数组$数组$格式)

解决方案

$源 - >执行($ sql中,数组(    '富'=> $ foo的,    '酒吧'=> $吧,    巴兹'=> $巴兹));

这是presuming上面的电话 PDOStatement对象::执行()引擎盖下,上述阵列作为参数。 1

:)

1)版本 5.2.17 和 5.3.8 在这里,并预期工作。

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 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 in a previously created array, however the keys contained aren't prefixed by the colon (:), and I figure there must be an elegant way to take:

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

And translate it into:

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

Without doing:

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

I've browsed the PHP docs, but I can't find a function (or sequence of) that suits the purpose.

Any ideas?

Addendum

Leaving the accepted answer, but +1 @chim for his clever 1-liner; solves the X in my XY problem. Reformatted solution:

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

Wrapped in a function, perhaps array_keys_format(array $array, $format)

解决方案

$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.

更多推荐

用字符串prefixing数组键(:)在PHP

本文发布于:2023-10-10 11:26:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1478532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用字   数组   prefixing   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!