我正在查询sql,响应反馈如下,以数组形式存储在$result_rows
中,
print_r($result_rows) - 显示以下二维数组
Array
(
[0] => Array
(
[employee_zipcode] => 70062
[employee_name] => Carter Jr
[employee_address] => 472 Shadowmar Drive Kenner, LA
[employee_id_series] => 6144
)
[1] => Array
(
[employee_zipcode] => 70062
[site_name] => Carter Sr
[address] => 472 Shadowmar Drive Kenner, LA
[employee_id_series] => 6144
)
[2] => Array
(
[employee_zipcode] => 29210
[site_name] => Claude
[address] => 2308 Wexford Way Columbia, SC
[employee_id_series]=> 6144
)
)
上面的动态结果是我通过6144
查询employee_id_series
得到的
我对如何对数组进行排序并将其打印到这种格式的 html 表感到困惑
期望的结果:
Emp Emp Emp
Zipcode_Series Name Address
70062_6144
70062_6144 Carter 472 Shadowmar Drive Kenner, LA
29210_6144 Claude 2308 Wexford Way Columbia, SC
注意:sorting_joining
是根据 employee_zipcode
值完成的,
在整个数组中交叉检查其相同的 value(70062)
。
最佳答案
一旦你使用了@Crayon 提到的usort
。您可以使用另一个关联数组来打印您想要的结果。这是一个粗糙的版本。希望它有所帮助。
usort($result_rows, 'cmp');
function cmp($row1, $row2) {
if ($row1['zipcode'] == $row2['zipcode']) {
return 0;
}
return ($row1['zipcode'] > $row2['zipcode']) ? -1 : 1;
}
//Create the printing_results as an associative array to keep the same zipcode together and increase the count.
$printing_results = array();
foreach ($result_rows as $result) {
$zipcode = $result['zipcode'];
$result['cnt'] = 1;
if (!isset($printing_results[$zipcode])) {
$printing_results[$result['zipcode']] = $result;
} else {
$printing_results[$result['zipcode']]['cnt'] = $printing_results[$result['zipcode']]['cnt'] + 1;
}
}
//For each associative array, print zipcode for other records and print all details on the last record.
foreach ($printing_results as $key => $printing_result) {
$cnt = $printing_result['cnt'];
for ($i=0; $i < $cnt; $i++) {
echo "\n".$printing_result['zipcode'];
}
print "\t".$printing_result['name']."\t".$printing_result['address'];
}
关于php - 使用列值对 php 数组进行排序并打印到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31127244/