PHP 数组到 postgres 数组 [英] PHP array to postgres array
问题描述
现在 php 不能直接使用 Postgresql 数组工作.例如,php采用postgresql数组,如'{"foo","bar"}'
Now php can't work directly wit Postgresql array. For example, php taking postgresql array like '{"foo","bar"}'
我需要简单的 php 函数来从 php 数组创建多维 postgresql 数组.
I need simple php function to create multidimensional postgresql array from php array.
我认为实验性的 pg_convert() 不是最优的,因为它需要额外的数据来形成用于数据库输出的简单数组字符串,也许我误解了这个函数的想法.
I think that experimental pg_convert() isn't optimal because it needs of extra data to form simple array string for database output, maybe I misunderstood the idea of this function.
比如我需要转换
$from=array( array( "par_1_1","par_1_2" ), array( "array_2_1", "array_2_2" ) );
$to='{{"par_1_1","par_1_2"},{"par_2_1","par_2_2"}}';
我可以使用 array_walk_recursive() 来转换数组最深的元素吗?
Can I use array_walk_recursive() to convert the deepest elements of array?
推荐答案
这里有一个简单的函数,用于将 PHP 数组转换为 PG 数组.
Here's a simple function for converting a PHP array to PG array.
function to_pg_array($set) {
settype($set, 'array'); // can be called with a scalar or array
$result = array();
foreach ($set as $t) {
if (is_array($t)) {
$result[] = to_pg_array($t);
} else {
$t = str_replace('"', '\\"', $t); // escape double quote
if (! is_numeric($t)) // quote only non-numeric values
$t = '"' . $t . '"';
$result[] = $t;
}
}
return '{' . implode(",", $result) . '}'; // format
}
这篇关于PHP 数组到 postgres 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!