首页 > 解决方案 > PHP转置关联数组并填充缺失的单元格?

问题描述

我有以下数据,其中包含种族的性别和年龄类别的特定结果。数据作为关联数组返回。

在大多数类别中,我有三个结果,但在某些类别中可能只有 1 或 2 个结果。

M50,1,9197,V50,M
M50,2,8253,V50,M
M50,3,18282,V50,M
W50,1,19961,V50,W
W50,2,7051,V50,W
W50,3,2480,V50,W
M55,1,7876,V55,M
M55,2,7640,V55,M
M55,3,19945,V55,M
W55,1,9029,V55,W
W55,2,6161,V55,W
W55,3,1172,V55,W
M60,1,7768,V60,M
M60,2,7112,V60,M
M60,3,7924,V60,M
W60,1,8747,V60,W
M65,1,7211,V65,M
M65,2,5234,V65,M
W65,1,8732,V65,W
M70,1,2952,V70,M
M70,1,2953,V70,W
M80,1,7953,V80,W

我想转置数组,以便每个类别显示为单行,每行最多 6 个结果,但任何缺失的行都用空白填充。

M50 M1, M50 M2, M50 M3, M50 W1, M50 W2, M50 M3
M55 M1, M55 M2, M55 M3, M55 W1, M55 W2, M55 M3
M60 M1, M60 M2, M60 M3, M60 W1, x     , x
M65 M1, M65 M2, x     , M65 W1, x     , x
M70 M1, x     , x     , M70 W1, x     , x
x     , x     , x     , M80 W1, x     , x

关于如何有效地实现这一目标有什么建议吗?

标签: phparrays

解决方案


这可能是您正在寻找的解决方案:

<?php

$data = array(
    array('M50',1,9197,'V50','M'),
    array('M50',2,8253,'V50','M'),
    array('M50',3,18282,'V50','M'),
    array('W50',1,19961,'V50','W'),
    array('W50',2,7051,'V50','W'),
    array('W50',3,2480,'V50','W'),
    array('M55',1,7876,'V55','M'),
    array('M55',2,7640,'V55','M'),
    array('M55',3,19945,'V55','M'),
    array('W55',1,9029,'V55','W'),
    array('W55',2,6161,'V55','W'),
    array('W55',3,1172,'V55','W'),
    array('M60',1,7768,'V60','M'),
    array('M60',2,7112,'V60','M'),
    array('M60',3,7924,'V60','M'),
    array('W60',1,8747,'V60','W'),
    array('M65',1,7211,'V65','M'),
    array('M65',2,5234,'V65','M'),
    array('W65',1,8732,'V65','W'),
    array('M70',1,2952,'V70','M'),
    array('M70',1,2953,'V70','W'),
    array('M80',1,7953,'V80','W')
);

function extractData($data)
{
    $result = array();
    $resultArrayTemplate = array('x', 'x', 'x', 'x', 'x', 'x');
    foreach($data as $item)
    {
        $value = $item[0] . ' ' . $item[4] . $item[1];
        $index = filter_var($item[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        if(isset($result[$index])) {
            if($result[$index][$item[1]-1] != x) {
                $subindex = $item[1]-1+3;
            } else {
                $subindex = $item[1]-1;
            }
            $result[$index][$subindex] = $value;
        } else {
            if($result[$index][$item[1]-1] != x) {
                $subindex = $item[1]-1+3;
            } else {
                $subindex = $item[1]-1;
            }
            $result[$index] = $resultArrayTemplate;
            $result[$index][$subindex] = $value;
        }
    }

    return $result;
}

print_r(extractData($data));

推荐阅读