用字符串prefixing数组键(:)在PHP [英] Prefixing array keys with a string (:) in PHP

查看:270
本文介绍了用字符串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对象::执行()引擎盖下,上述阵列作为参数。<​​SUP> 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆