PHP explode() returns array inside array
PHP explode() returns array inside an array
我有以下功能:
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']);
然后分解returns一个数组,结果就是你在做的。
把变量名中的“[]”去掉,问题就解决了
您将 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 [];
}
}
我有以下功能:
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']);
然后分解returns一个数组,结果就是你在做的。
把变量名中的“[]”去掉,问题就解决了
您将 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 [];
}
}