开发者

Transforming array into smaller arrays

开发者 https://www.devze.com 2023-03-20 04:38 出处:网络
I\'ve been breaking my head over this problem all day. How can I transform the following开发者_JAVA技巧 array:

I've been breaking my head over this problem all day. How can I transform the following开发者_JAVA技巧 array:

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
    )
)

Into an array with this format:

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

The former is being returned by a function. Please note that the 0 in the latter array isn't there in the former array. I do however need to preserve the key values. I've been trying several array functions to make it work but I just cant seem to solve the problem. Any help would be very much appreciated.

Let me try elaborating a bit. The latter array is used as input to create a table. The table would look like something as:

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


If I understand the desired result:

$result = array();

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

print_r($result);


This is how I understand the desired result, the question drops one item from the array, so I'm not totally sure. And it changes the keys, so perhaps needs some key aliasing later on:

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


$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;
            }
        }
    }
}

I'm pretty sure this could be optimized further, not least by targeting a different array format, but this should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号