我在$result_rows
中存储的数组格式中查询sql和响应反馈如下,
print_r($ result_rows) - 显示以下2D数组
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
)
)
当我通过employee_id_series
6144
时,会获得上述动态结果
我对如何对数组进行排序并以此格式将其打印到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)
。
答案 0 :(得分:1)
使用@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'];
}
答案 1 :(得分:0)
您可以使用usort按二级数组元素进行自定义排序:
usort($result_rows, function($a, $b)
{
if ($a['employee_zipcode'] == $b['employee_zipcode'])
return 0;
else if ($a['employee_zipcode'] > $b['employee_zipcode'])
return -1;
else
return 1;
});
从那里..我不知道为什么你真的想要/需要合并employee_zipcode
和employee_id_series
..似乎更好,你应该将它们分开并且只是在演示中连续但我认为是如果你真的想要那个......你可以做些微不足道的事情。
不想在sql中排序,php数组需要比较那些70062 输入查询6144并将这些匹配转储到单个表行
您需要在一行中显示多个70062_6144
是否有任何特殊原因?如果没有,您只需array_unique
排序的数组。