1

所以我遇到了这个奇怪的问题,我不知道是什么原因造成的。我们在 PHP 中使用 Charts.js 来绘制一些图表。我们将创建图表所需的参数存储到 PSQL 表中,以便在需要时加载。

我的问题在于标题、组和标签参数,它们都是字符串数组。它们存储在 text[] 表中。问题是,当我查询图形的参数时,如果数组中的字符串有空格,则在引号之间返回,否则作为字符串本身返回。

我有一个关联数组 $graph ,它存储图形的参数并用于将值插入数据库:

$cursor = $this->query("
        INSERT INTO data.graphs(region,title,type,section,label,group,values,colors,id_sample)                   
        VALUES(
            '".$graph['local']."',
            '".$graph['title']."',
            '".$graph['type']."',
            '".$graph['section']."',
            '".$graph['label']."',
            '".$graph['group']."',
            '".$graph['values']."',
            '".$graph['colors']."',
            '".$_SESSION['id_sample']."'
        )  
    "); 

插入数据库的字符串数组是这样的:

$graph1['label'] = "{Não há material presente,Material presente, mas crianças não usaram,Crianças usaram os materiais}";
$graph2['label'] = "{Boa vista, Rural, Urbana, Indigena}";
$graph3['label'] = "{Boa vista, Ru ral, Urb ana, Ind igena}";

如果我在数据库中查询我的标签,它们看起来像这样:

在此处输入图像描述

现在要查询数据,我们对所需的每个图形的参数执行“SELECT *”并再次存储它们的值关联数组(用作 Charts.js 绘图仪的参数)。

$aux = pg_fetch_array($cursor))
print_r($aux['label']);

这就是我的 3 个图表中每个图表的标签的样子:

{"Não há material presente","Material presente, mas crianças não usaram","Crianças usaram os materiais"}
{"Boa vista",Urbana,Rural,Indigena}
{"Boa vista","Urb ana","Ru ral","Ind igena"}

所以在数据库中,字符串没有引号,如果一个 qstring 有一个空格,它会在引号之间返回,这并不全是坏的,因为我希望我的字符串用引号引起来。

有没有办法强制数组中返回的每个字符串都在所有引号内?

我已经尝试将这样的数组插入数据库:

$graph['label'] = "{
        \"Boa vista\",
        \"Urbana\",
        \"Rural\",
        \"Indigena\"
    }";

如果我查看数据库,字符串没有引号,它们会再次像上面一样返回。

4

1 回答 1

2

That's the default text output for type text[]. The manual:

The array output routine will put double quotes around element values if they are empty strings, contain curly braces, delimiter characters, double quotes, backslashes, or white space, or match the word NULL. Double quotes and backslashes embedded in element values will be backslash-escaped.
[...] for textual data types one should be prepared to cope with either the presence or absence of quotes.

If you prefer a text representation with all elements double quoted, you could use a simple expression like:

SELECT '"' || array_to_string('{"Boa vista",Urbana,Rural,Indigena}'::text[], '", "') || '"'

If you need it a lot, consider a (simplistic) function:

CREATE OR REPLACE FUNCTION f_array_to_string_with_quotes(_arr text[], _quote text = '"')
  RETURNS text LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
$func$
SELECT $2 || array_to_string($1, $2 || ', ' || $2) || $2
$func$;

Call:

SELECT f_array_to_string_with_quotes('{"Boa vista",Urbana,Rural,Indigena}', '"');
| f_array_to_string_with_quotes              |
| :----------------------------------------- |
| "Boa vista", "Urbana", "Rural", "Indigena" |

db<>fiddle here - with more examples

Note that the resulting type is now text, not text[]! And it does not properly escape anything, hence "simplistic".

于 2020-05-10T02:46:59.440 回答