php - 使用列值对 php 数组进行排序并打印到表中

标签 php html arrays

我正在查询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/

相关文章:

php - 在 PHP 7.0 中 fatal error : Uncaught Error: Call to undefined function json_encode()

python - 如何使用随机数打印设置新记录(在数组内)的时间

使用C代码计算库仑定律

javascript - 循环遍历对象数组并返回这些对象的累积数据

php - 从 PHP 中的表中获取主题

PHP SQL SELECT where like 搜索带有多个词的项目

javascript - 使用 PHP ajax 调用后执行 Chartjs

html - 仅在 iPad View 中显示的列之间的垂直间隙

javascript - 如何在客户端使用 HTML 和 Javascript 验证文件大小

php - 带有 Ratchet 的 Redis 发布订阅