Patrioticcow
Patrioticcow

Reputation: 27058

how to group together arrays based on a value in php?

I have thee following $array:

Array
(
[0] => Array
    (
        [cd] => 1675
        [amt_1] => 199.50
        [fname] => Joe
        [lname] => A
    )

[1] => Array
    (
        [cd] => 1675
        [amt_1] => 69.90
        [fname] => Joe
        [lname] => A
    )

[2] => Array
    (
        [cd] => 1676
        [amt_1] => 69.90
        [fname] => Tracy
        [lname] => A
    )

[3] => Array
    (
        [cd] => 1676
        [amt_1] => 199.50
        [fname] => Tracy
        [lname] => A
    )
...
)

I am trying to do is to group them together, in this case, by fname or cd so that i will have something like:

[0] => Array
    (
        [cd] => 1676
        Array
            (
            [0] => Array
                 (
                 [amt_1] => 199.50
                 )
            [1] => Array
                 (
                 [amt_1] => 69.90
                 )
        [fname] => Joe
        [lname] => A
    )
  [1] => Array
    (
        [cd] => 1676
        Array
            (
            [0] => Array
                 (
                 [amt_1] => 199.50
                 )
            [1] => Array
                 (
                 [amt_1] => 69.90
                 )
        [fname] => Tracy
        [lname] => A
    )
    ........   

I can't seem to figure it out. This cannot be done in mysql, I need to do it in php.

Any ideas?

Thanks

edit: I know that the result example is not formatted correct, but basically I want to combine the fname and the rest of results place them in arrays.

edit:

@Paulo H has a good idea. also i found another way of doing it that groups it together not combining it :

$groups = array ();
    foreach ( $the_array as $item ) {
        $key = $item ['fname'];
        if (! isset ( $groups [$key] )) {
            $groups [$key] = array ('items' => array ($item ), 'count' => 1 );
        } else {
            $groups [$key] ['items'] [] = $item;
            $groups [$key] ['count'] += 1;
        }
    }

Upvotes: 2

Views: 246

Answers (1)

Paulo H.
Paulo H.

Reputation: 1258

Try this:

function &array_group_value_by($input_array,$value,$by){
    $result = array();
    foreach($input_array as $array){
        if(!isset($result[$array[$by]])){
            $result[$array[$by]] = array();
        }
        foreach($array as $key=>$data){
            if((is_string($value) && $key==$value) || (is_array($value) && in_array($key,$value))){
                if(!isset($result[$array[$by]][$key])){
                    $result[$array[$by]][$key] = array();
                }
                $result[$array[$by]][$key][] = $data;
            }else{
                $result[$array[$by]][$key] = $data;
            }
        }
    }
    return $result;
}

$grouped = array_group_value_by($yourarray,'amt_1','fname');
print_r($grouped);

Upvotes: 1

Related Questions