我希望在具有相同供应商ID的情况下将我的阵列分组为子阵列。我在这里看了很多类似的问题,但我不能让它们为我工作。我尝试了foreach循环甚至PHP合并功能。我必须使用MySQLi,所以我不能使用PDO进行分组。
这就是我所拥有的:
Array
(
[supplierID] => 1
[drugID] => 1
[costPrice] => 9.98
[reorderQTY] => 50
)
Array
(
[supplierID] => 1
[drugID] => 2
[costPrice] => 9.98
[reorderQTY] => 50
)
Array
(
[supplierID] => 2
[drugID] => 3
[costPrice] => 9.98
[reorderQTY] => 50
)
这就是我需要的:
Array
(
[supplierID] => 1
Array
(
[drugID] => 1
[costPrice] => 9.98
[reorderQTY] => 50
)
[drugID] => 2
[costPrice] => 9.98
[reorderQTY] => 50
)
)
Array
(
[supplierID] => 2
Array
(
[drugID] => 3
[costPrice] => 9.98
[reorderQTY] => 50
)
)
这是我输出数组的PHP,以获得上述结果:
if(isset($_POST["automatic"])){
$sql = "SELECT supplierID,drugID,costPrice,reorderQTY FROM drugs WHERE quantityInStock <= reorderLevel";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<pre>";
print_r($row);// I need to sort this array into sub array groups by supplierID key
echo "</pre>";
}
}else{
echo " <tr><td>0 results </td></tr>";
}
mysqli_close($conn);
}
答案 0 :(得分:3)
这样的事情会做到,
$out = [];
while($row = mysqli_fetch_assoc($result)) {
$out[$row->supplierID][] = $row;
}
基本上我使用supplier id创建一个数组键,然后分配一个空数组。然后将具有该供应商ID的所有行添加到该数组。
这将创建一个多维数组。