我正在用PHP玩一个数组(还在学习数组!)
我有以下PHP代码从我的eventsTest表中提取数据,并回显数组;
<?php
if ($result = $con->query("SELECT * FROM eventsTest")) {
$array = array();
while($row=mysqli_fetch_assoc($result)) {
$array[] = $row;
}
print "<pre>";
print_r($array);
print "</pre>"; // DEBUG--- show all array data
}
将我的数组打印为:
Array
(
[0] => Array
(
[id] => 1
[dateStart] => 2018-12-26
[dateEnd] => 2018-12-26
[name] => Test Event 1
)
[1] => Array
(
[id] => 2
[dateStart] => 2018-12-27
[dateEnd] => 2018-12-27
[name] => Test Event 2
)
)
代替[0] [1] [2]键作为索引,我可以将dateStart设置为数组索引的键吗?
例如:
Array
(
[2018-12-26] => Array
(
[0] => Array
(
[dateEnd] => 2018-12-27
[name] => Test Event 1
)
)
[2018-12-27] => Array
(
[0] => Array
(
[dateEnd] => 2018-12-27
[name] => Test Event 2
)
)
[2018-12-28] => Array
(
[0] => Array
(
[dateEnd] => 2108-12-28
[name] => Test Event 3
)
[1] => Array
(
[dateEnd] => 2018-12-28
[name] => Test Event 4
)
)
)
例如,如果有多个行具有相同的dateStart,是否也将dateStart分组在同一索引中?
答案 0 :(得分:2)
赞:
while($row=mysqli_fetch_assoc($result)) {
$array[$row['dateStart']][] = $row;
}
请注意,这将为您提供类似于您所要求的结构。
Array
(
[2018-12-26] => Array
(
[0] => Array
(
[dateEnd] => 2018-12-27
[name] => Test Event 1
)
)
因为此$array[$row['dateStart']][] =
是带有键$array[$row['dateStart']]
的数组$row['dateStart']
,所以它的值是包含行的数组。
答案 1 :(得分:1)
您可以这样做:
<?php
if ($result = $con->query("SELECT * FROM eventsTest")) {
$array = [];
while($row=mysqli_fetch_assoc($result)) {
if (isset($row['dateStart'])) {
$array[$row['dateStart']] = $row;
}
}
print "<pre>";
print_r($array);
print "</pre>"; // DEBUG--- show all array data
}