如何从数据库

时间:2016-07-10 14:16:05

标签: php mysql arrays mysqli

我有以下mysqli查询,并且我希望将输出的数组内爆为(1,2,3,4)类型格式。

这里是查询和asoc数组代码:

$user_categories = mysqli_query($connect, "SELECT sub_cat FROM subscriptions WHERE sub_user_id = '$user_id'");

$category_ids = mysqli_fetch_all($user_categories,MYSQLI_NUM);

print_r($category_ids);

$category_ids = implode(", ",$category_ids);

然后我得到以下输出,我似乎无法隔离值...

Array ( 
[0] => Array ( [0] => 5 ) 
[1] => Array ( [0] => 8 ) 
[2] => Array ( [0] => 4 ) 
[3] => Array ( [0] => 2 ) 
)

如果我在这里遗漏了一些非常明显的东西,请道歉。我一直试图解决这个问题,由于我缺乏PHP经验,我不能100%确定要搜索的内容。

我还使用$user_categories查询的结果尝试了一个简单的内爆,遵循我在该主题上看到的其他StackExchange答案的说明,但没有得到任何结果(下面的代码):

$user_categories = mysqli_query($connect, "SELECT sub_cat FROM subscriptions WHERE sub_user_id = '$user_id'");

$category_ids = implode(", ",$user_categories);

echo $category_ids;

3 个答案:

答案 0 :(得分:4)

$category_ids是一个数组(行)数组,所以你不能破坏它。您需要从每一行获取第一个值并将其内爆。

PHP 5.5+解决方案:

使用array_column()

$category_ids = implode(', ', array_column($category_ids, 0));

echo $category_ids;

输出:

  

5,8,4,2

PHP 5.3+解决方案:

array_map()代替array_column()

$category_ids = implode(', ', array_map(function ($row) { return $row[0]; }, $category_ids));

echo $category_ids;

输出:

  

5,8,4,2

答案 1 :(得分:2)

$category_ids得到的

mysqli_fetch_all是数组数组,只是将其传递给implode无法检索到所需的结果。但是,这应该做的工作:

$category_ids = mysqli_fetch_all($user_categories,MYSQLI_NUM);

$category_ids_imploded = implode(', ', array_map(function ($entry) {
  return $entry['0'];
}, $category_ids));

或者,如果您使用的是PHP 5.5或更高版本,则可以使用array_column来减少麻烦:

$category_ids_imploded = implode(', ', array_column($category_ids, 0));

答案 2 :(得分:0)

Mysql解决方案

$sql = "SELECT group_concat(sub_cat) FROM subscriptions WHERE sub_user_id = '$user_id'"
$result = mysqli_query($connect, $sql);
$category_ids = mysqli_fetch_row($user_categories)[0];

PDO溶液(优选)

$sql = "SELECT group_concat(sub_cat) FROM subscriptions WHERE sub_user_id = ?"
$stmt = $connect->prepare($sql);
$stmt->execute([$user_id]);
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
$category_ids = implode(",", $array);