如何:连接从mysql查询生成的php数组?

ffdz8vbo  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(256)

我正在使用mysql/php开发一个播放器名生成器。如何将一列(不包括主键)表的值选择到一维数组中,然后连接数组的值?
“音节开头”示例表:

characters
t
d
ch

PHP代码

$syllable = array("","","");

$sql = "SELECT characters FROM syllableInitials";
$result = $conn->query($sql);

$syllableInitials = array();

while ($initial = mysqli_fetch_row($result)) {
    $syllableInitials[] = $initial;
}
$syllableMedials = array("a", "o", "i");
$syllableFinals = array("m","s","d");

$syllable[0] = $syllableInitials[0] . $syllableMedials[2] . $syllableFinals[0];

echo "Syllable is: <b>" . $syllable[0] . "</b>";

我得到的结果是:
注意:数组到字符串的转换在第行。。。音节is:arrayim
显然,我对上述示例代码的预期输出是“tim”而不是“arrayim”。
音节开头数组的打印生成。。。

Array (
     [0] => Array ( [0] => t )
     [1] => Array ( [0] => d ) 
    [2] => Array ( [0] => ch )
)

所以看起来好像我无意中嵌套了这个数组,或者导致它是二维的!我的代码真的生 rust 了。。。提前谢谢!

c86crjj0

c86crjj01#

这应该给你“提姆”:

$syllable[0] = $syllableInitials[0][0] . $syllableMedials[2] . $syllableFinals[0];

在代码中,您只指向[0]中的另一个数组;

Array (
     [0] =>**Array ( [0] => t )**
     [1] => Array ( [0] => d ) 
     [2] => Array ( [0] => ch )
)

所以你有两个选择。。
第一:

$syllable = array("","","");

$sql = "SELECT characters FROM syllableInitials";
$result = $conn->query($sql);

$syllableInitials = array();

while ($initial = mysqli_fetch_row($result)) {
    $syllableInitials[] = $initial[0];
}
$syllableMedials = array("a", "o", "i");
$syllableFinals = array("m","s","d");

$syllable[0] = $syllableInitials[0] . $syllableMedials[2] . $syllableFinals[0];

echo "Syllable is: <b>" . $syllable[0] . "</b>";

第二:

$syllable = array("","","");

$sql = "SELECT characters FROM syllableInitials";
$result = $conn->query($sql);

$syllableInitials = array();

while ($initial = mysqli_fetch_row($result)) {
    $syllableInitials[] = $initial;
}
$syllableMedials = array("a", "o", "i");
$syllableFinals = array("m","s","d");

$syllable[0] = $syllableInitials[0][0] . $syllableMedials[2] . $syllableFinals[0];

echo "Syllable is: <b>" . $syllable[0] . "</b>";
2ic8powd

2ic8powd2#

因为$initial是一个数组,并且有一个元素,所以您可以执行以下操作:

$syllableInitials[] = $initial[0];

但更好的解决方案是将pdo与其pdostatement::fetchcolumn函数一起使用。
例如:

$syllable = array("","","");

$options = array(
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);

$dbh = new PDO('mysql:dbname=dbname;host=127.0.0.1', 'username', 'password', $options);

$sth = $dbh->prepare('SELECT characters FROM syllableInitials');
$sth->execute();

$syllableInitials = array();

while ($initial = $sth->fetchColumn()) {
    $syllableInitials[] = $initial;
}
$syllableMedials = array("a", "o", "i");
$syllableFinals = array("m","s","d");

$syllable[0] = $syllableInitials[0] . $syllableMedials[2] . $syllableFinals[0];

echo "Syllable is: <b>" . $syllable[0] . "</b>";

相关问题