英文:
How can I efficiently work with arrays from php while loop?
问题
我有一个包含列a、b、c的php Sqlite3表,并且我想构建一个由这些列组成的数组。
在获取php Sqlite3中的列名并将结果编码为Json之后,我得到了以下格式的输出:
["a"]["a","b"]["a","b","c"]
我的想法是构建一个这种形式的数组 ["a","b","c"]
,或者获取上述输出中最后一个方括号的内容。
我是否漏掉了任何步骤,或者我应该如何获得所需的输出?
以下是我的php代码:
<?php
// Database name
$database_name = "my_sqlite.db";
// Database Connection
$db = new SQLite3($database_name);
// Create Table "students" into Database if not exists
$query = "CREATE TABLE IF NOT EXISTS students (a STRING, b STRING, c STRING)";
$db->exec($query);
?>
<?php
$tablesquery = $db->query("PRAGMA table_info(students);");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
//$r[] = $table['Field'];
$ary[] = $table["name"];
$colns = json_encode($ary);
echo $colns;
//this gives ["a"]["a","b"]["a","b","c"]
//my desired output ["a","b","c"];
}
?>
英文:
I have a table of columns; a, b, c in php Sqlite3 and I want to construct an array consisting of those columns.
After fetching the column names in php Sqlite3 and encoding the results to Json, am getting the output of the following format;
["a"]["a","b"]["a","b","c"]
My idea is to construct an array of this form ["a","b","c"]
or perhaps get contents of the last square bracket in the above output.
Is there any step I am missing or how should I get my required output?
Below is my php code;
<?php
// Database name
$database_name = "my_sqlite.db";
// Database Connection
$db = new SQLite3($database_name);
// Create Table "students" into Database if not exists
$query = "CREATE TABLE IF NOT EXISTS students (a STRING, b STRING, c STRING)";
$db->exec($query);
?>
<?php
$tablesquery = $db->query("PRAGMA table_info(students);");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
//$r[] = $table['Field'];
$ary[] = $table["name"];
$colns = json_encode($ary);
echo $colns;
//this gives ["a"]["a","b"]["a","b","c"]
//my desired output ["a","b","c"];
}
?>
答案1
得分: 1
在你的 while 循环中,你每次将一个行名称添加到 $ary 数组中。并且你在每次 while 循环迭代中打印该数组,所以你看到了那个输出。
你应该做的是循环将名称添加到数组中,但只在循环完成后打印一次。
像这样:
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
//$r[] = $table['Field'];
$ary[] = $table["name"];
}
$colns = json_encode($ary);
echo $colns;
在循环内部执行 echo
会显示数组正在构建的过程,而不仅仅是最终的内容,就像上面的代码那样。
英文:
In your while loop, you add one row name at a time into the $ary array. And you print the array in each iteration of the while loop, so it makes sense you see that output.
What you should do is loop to add names into the array, but only print it once, after the while is completed.
Like this:
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
//$r[] = $table['Field'];
$ary[] = $table["name"];
}
$colns = json_encode($ary);
echo $colns;
Performing the echo
inside the loop showed you the array being built, not just the final content, like the code above does.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论