Php 每天从mysql数据库向数组中添加元素
如何将数据库中的记录值按数组中的这种方式排序。谢谢,我加上了第二天Php 每天从mysql数据库向数组中添加元素,php,mysql,arrays,date,Php,Mysql,Arrays,Date,如何将数据库中的记录值按数组中的这种方式排序。谢谢,我加上了第二天 array [0] => array=>'id'=>'26' 'date'=>'26' [1] => array=>'id'=>'27' 'date'=>'27', array=>'id'=>'28' 'date'=>'27', array=>'id'=>'29' 'date'=>'27' [2] =&g
array
[0] => array=>'id'=>'26' 'date'=>'26'
[1] => array=>'id'=>'27' 'date'=>'27',
array=>'id'=>'28' 'date'=>'27',
array=>'id'=>'29' 'date'=>'27'
[2] => array=>'id'=>'30' 'date'=>'29'
[3] => array=>'id'=>'31' 'date'=>'31',
array=>'id'=>'32' 'date'=>'31',
array=>'id'=>'33' 'date'=>'31'
基本上,如果下一个id包含一个月的相同日期(日期号)的记录,我想向相同的索引添加一个数组。否则正常添加
现在,我的函数是添加记录的行,而不是按照我希望的格式对其进行排序
我希望它采用这种格式的原因是,我需要运行foreach,如果1天包含2条记录,那么它会将另一条记录附加到我的无序列表中
public function getArticles()
{
$sql = 'CALL getArticles()';
$articles = Array();
if (Model::getConnection()->multi_query($sql)) {
do {
if ($result = Model::getConnection()->store_result()) {
while ($row = $result->fetch_assoc()) {
array_push($articles,$row);
}
$result->free();
}
} while (Model::getConnection()->next_result());
}
return $articles;
}
我不知道您的一些代码在做什么,但我认为这是重要的部分
while ($row = $result->fetch_assoc()) {
if (!isset($articles[$row['date']])) {
$articles[$row['date']] = array();
}
$articles[$row['date']][] = $row;
}
唯一的区别是数组将键入日期
,而不是从零开始递增。如果你真的想重新编制索引,你可以
array_values($articles);
正如savinger所指出的,您的代码中有很多功能我不太清楚,因此我加入了一些注释,以指示流程的位置:
// Start of your loop
// $value is what you're getting from the DB...
$array_search = array_search($value,$main_array);
if($array_search)
{
// If this value already exists, we need to add
// this value in +1 of its current value
$main_array[$array_search][] = $value + 1;
}
else
{
// Make a new array key and add in the value
$main_array[] = $value;
}
// End of your loop