将数组转换为更小的数组

时间:2011-07-12 12:38:07

标签: php arrays transform

我整天都在解决这个问题。 如何转换以下数组:

Array
(
[0] => Array
    (
        [compId] => 3081
        [category] => Products
        [rev] => 0.61
    )

[1] => Array
    (
        [compId] => 3080
        [category] => Plants
        [rev] => 51
    )

[2] => Array
    (
        [compId] => 3080
        [category] => Products
        [rev] => 6.1
    )
)

使用以下格式的数组:

Array( 
'compId'=>array("3081","3080"), 
'Products'=>array('0.61', '6.1'), 
'Plants'=>array('0', '51')
);

前者由函数返回。请注意,后一个数组中的0不在前一个数组中。但我确实需要保留键值。我一直在尝试几个数组函数来使它工作,但我似乎无法解决问题。 非常感谢任何帮助。

让我试着详细说明一下。后一个数组用作创建表的输入。 该表看起来像:

CompID | Products | Plants
__________________________
3081   | 0.61     | 0
__________________________
3080   | 6.1      | 51

3 个答案:

答案 0 :(得分:1)

如果我理解了所需的结果:

$result = array();

foreach ( $array as $item ) {
    $result['compId'][] = $item['compId'];
    $result[$item['category']][] = $item['rev'];
}

print_r($result);

答案 1 :(得分:0)

这就是我理解所需结果的方法,问题是从数组中删除一个项目,所以我不完全确定。它会改变键,所以稍后可能需要一些键别名:

foreach ( $array as $item )
    foreach( $item as $key => $value)
        $result[$key][] = $value
;

答案 2 :(得分:0)

$categories = array_unique(array_map(function ($elem) { return $elem['category']; }, $array));
$tableRows = array('compId' => array_values(array_unique(array_map(function ($elem) { return $elem['compId']; }, $array))));

foreach ($tableRows['compId'] as $i => $compId) {
    foreach ($categories as $category) {
        $tableRows[$category][$i] = 0;
        foreach ($array as $elem) {
            if ($elem['category'] == $category && $elem['compId'] == $compId) {
                $tableRows[$category][$i] = $elem['rev'];
                break;
            }
        }
    }
}

我很确定这可以进一步优化,尤其是针对不同的数组格式,但这应该可行。