我有一个 MySQL 数据库,其中有一个名为 users 的表,我需要将其组成一个数组。但它必须能够处理重复值。
当它发现重复值时,它会将这些值连接到一个键下。不过,我只需要加入 user_id 列中的值,因为这将是一个电子商务网站,人们一次可以购买不止一件商品。
这是我的数据库的样子,特别是名为队列的表:
Table Queue:
user_id, item_id
100, 103850
100, 103850
100, 129374
101, 303213
101, 103850
不过我需要它,返回一个看起来像这样的数组:
array(
100 => array(
'items' => array(
array('item_id' => 103850),
array('item_id' => 103850),
array('item_id' => 129374),
),
),
101 => array(
'items' => array(
array('item_id' => 303213),
array('item_id' => 103850),
),
),
);
现在这是我正在使用的代码,它是我从之前问过的另一个问题中得到的,但它并没有真正完整地回答我的问题。
<?php
function getAllUsers() {
$data_from_db = array(
100 => array(
'items' => array(
array('item_id' => 103850),
array('item_id' => 103850),
array('item_id' => 129374),
),
),
101 => array(
'items' => array(
array('item_id' => 303213),
array('item_id' => 103850),
),
),
);
// while loop fetch to array blah blah
$users = $data_from_db;
return $users;
}
if(isset($_GET['jsoncallback'])) {
$data = getAllUsers();
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
?>
上面代码的问题在于它是手动输入到 PHP 脚本中的,而不是使用 MySQL 查询生成的。我希望它使用 MySQL 查询生成,但我在弄清楚如何这样做时遇到了很多麻烦。
最佳答案
你只需要做一个简单的查询。按照这个例子:
function getAllUsers() {
$data = array();
// host - username - password - database
$connection = new mysqli('localhost', 'test', 'test', 'test');
$query = mysqli_query($connection, 'SELECT `user_id`, `item_id` FROM `table_queue`');
while($row = $query->fetch_assoc()) {
$data[$row['user_id']]['items'][] = array('item_id' => $row['item_id']);
}
return $data;
}
if(isset($_GET['jsoncallback'])) {
$data = getAllUsers();
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
?>
当您调用 http://yoursite.com?jsoncallback
时,您会得到如下信息:
{"100":{"items":[{"item_id":"103850"},{"item_id":"103850"},{"item_id":"129374"}]},"101":{"items":[{"item_id":"303213"},{"item_id":"103850"}]}}
关于php - 从具有重复值的 MySQL 在 PHP 中创建关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24004976/