组数组值和循环

时间:2017-05-25 18:01:15

标签: php mysql

我有一个MySQL表,存储了与某年相关的数据

表名:registrations

id   name     year     address    
1    Tom      2011     NY   
2    Peter    2012     NY   
3    harry    2011     NY   
4    Steve    2012     NY   
5    Tommy    2013     NY   
6    Steph    2013     NY   
7    Sean     2011     NY 

我使用以下查询从表中获取数据

select * from registrations ORDER by year ASC 

在我的PHP代码上我使用foreach循环来遍历数组值

问题是我希望按年显示记录,例如

year - 2011
       Name: Tom
       Address: NY

       Name: Harry
       Address: NY

       Name: Sean
       Address: NY

Year - 2012
       Name: Peter
       Address: NY

 ............

有人可以告诉我实现这个目标的最佳途径是什么?

1 个答案:

答案 0 :(得分:0)

第一步是按照您希望对其进行分组的方式对所有数据进行分组。 $records变量模拟mysql返回的变量。最后的循环只是创建一个新数组,其中year作为人员信息的关键和子数组。这样可以很容易地循环并以指定的格式打印出您想要的值。

$records = [
    [
        'id' => 1,
        'name' => 'Tom',
        'year' => 2011,
        'address' => 'NY'
    ],
    [
        'id' => 2,
        'name' => 'Peter',
        'year' => 2012,
        'address' => 'NY'
    ],
    [
        'id' => 3,
        'name' => 'harry',
        'year' => 2011,
        'address' => 'NY'
    ],
    [
        'id' => 4,
        'name' => 'Steve',
        'year' => 2012,
        'address' => 'NY'
    ],
    [
        'id' => 5,
        'name' => 'Tommy',
        'year' => 2013,
        'address' => 'NY'
    ],
    [
        'id' => 6,
        'name' => 'Steph',
        'year' => 2013,
        'address' => 'NY'
    ],
    [
        'id' => 7,
        'name' => 'Sean',
        'year' => 2011,
        'address' => 'NY'
    ],
];


$byYear = [];
foreach ($records as $record) {
    $year = $record['year'];
    $person = ['Name' => $record['name'], 'Address' => $record['address']];
    if (!isset($byYear[$year])) {
        $byYear[$year] = [];
    }
    array_push($byYear[$year], $person);
}