PHP爆炸()返回一个数组内数组
问题描述:
我有以下功能:PHP爆炸()返回一个数组内数组
function GetTagsOfUser(){
require "include/connect.php";
$sql = "SELECT * FROM users WHERE User='Chona'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()){
$tagsOfUser[] = explode(';', $row['Tags']);
}
return $tagsOfUser;
}
,把它进行打印
print_r($Recomend->GetTagsOfUser());
时,我得到如下:
array(1) { [0]=> array(4) { [0]=> string(6) "Paises" [1]=> string(7) "Francia" [2]=> string(19) "Revolucion Francesa" [3]=> string(3) "ONU" } }
它看起来好像在我的数组中包含字符串的数组,我想有一个数组,请帮助。
答
变量$ tagsOfUser []是一个数组:
$tagsOfUser[] = explode(';', $row['Tags']);
而且爆炸返回一个数组,其结果是,你在做什么。
从变量名称中除去“[]”,问题就解决了。
+0
*从变量名中删除“[]”,问题就会解决。* - 两行发生了什么? –
答
您可以设置从explode
结果阵列到另一个阵列($tagsOfUser
):
$tagsOfUser[] = explode(';', $row['Tags']);
可以使用array_merge
来解决这个问题:
$tagsOfUser = array_merge($tagsOfUser, explode(';', $row['Tags']));
function GetTagsOfUser() {
require "include/connect.php";
$sql = "SELECT * FROM users WHERE User='Chona'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$tagsOfUser= [];
while ($row = $result->fetch_assoc()){
$tagsOfUser = array_merge($tagsOfUser, explode(';', $row['Tags']));
}
return $tagsOfUser;
}
}
你只需要/需要一行(对于特定用户)?
在这种情况下,你不需要while
环或$tagsOfUser
变量:
function GetTagsOfUser() {
require "include/connect.php";
$sql = "SELECT TOP 1 * FROM users WHERE User = 'Chona'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
return explode(';', $row['Tags']);
} else {
return [];
}
}
这可能是因为这行:'$ tagsOfUser [] =爆炸(...)' 如果你改变这一行为'return explode(...)',你将有一个单一的水平数组 –
$ tagsOfUser [] .. []创建它? –