现在php不能直接用Postgresql数组工作。例如,php采用类似postgresql的数组
'{“foo”,“bar”}'
我需要简单的php函数来从php数组创建多维postgresql数组。
我认为实验性pg_convert()并不是最佳的,因为它需要额外的数据来形成用于数据库输出的简单数组字符串,也许我误解了此函数的概念。
例如,我需要转换
$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()转换数组的最深层元素吗?
最佳答案
这是一个将PHP数组转换为PG数组的简单函数。
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数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5631387/