views:

58

answers:

2
+3  Q: 

php array combine

I have the next array:

Array
(
    [0] => Array
        (
            [id] => 160
            [payment_period] => Monthly
            [plan_payment_type_id] => 171
            [payment_type_id] => 4
        )
    [1] => Array
        (
            [id] => 160
            [payment_period] => Monthly
            [plan_payment_type_id] => 172
            [payment_type_id] => 5
        )
    [2] => Array
        (
            [id] => 161
            [payment_period] => Weekly
            [plan_payment_type_id] => 173
            [payment_type_id] => 9
        )
)

I need to group this array by id. How can I do it in the best way? My output should be:

Array
(
    [0] => Array
        (
            [id] => 160
            [payment_period] => Monthly
            [payment_types] => Array(
                [0] => Array(
                    [plan_payment_type_id] => 171
                    [payment_type_id] => 4
                )
                [1] => Array(
                    [plan_payment_type_id] => 172
                    [payment_type_id] => 5
                )
            )
        )
    [1] => Array
        (
            [id] => 161
            [payment_period] => Weekly
            [payment_types] => Array(
                [0] => Array(
                    [plan_payment_type_id] => 173
                    [payment_type_id] => 9
                )
            )
        )
)

Thank you very much.

+3  A: 

Something like this:

$output = array();
$id_array = array();
$i = 0;
foreach($input as $key=>$val) {
        if(array_key_exists($val['id'],$id_array)) {
                $pos = $id_array[$val['id']];
                $output[$pos]['payment_types'][] = array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id']);
        } else {
                $output[$i] = array('id' => $val['id'],'payment_period' => $val['payment_period'],'payment_types' => array(array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id'])));
                echo "Adding ",$val['id'],"\n";
                $id_array[$val['id']] = $i; 
                $i++;
        }   
}

Working link

codaddict
+1  A: 

You are stuck because you try to build an enumarated array, when you actually want to groups this by array id. Just use the "id" field as target index:

foreach ($in as $src) {
    extract($src);
    $output[$id]["id"] = $id;
    $output[$id]["payment_period"] = $payment_period;
    $output[$id]["payment_types"][] = array(
        "plan_payment_type_id" => $plan_payment_type_id,
        "payment_type_id" => $payment_type_id,
    );
}

Of course you can use lengthy $src[] variable names instead of the evil extract() shortcut.

Anyway, this method groups your output array by $id, but also retains the "id"=>$id internal key.

mario