0

How to encode an associative array grouping one of its members?

$my_array = Array(
// customer 1
    [0] => Array
        (
            [customer_id] => 1
            [cutomer_item] => 7
        )

    [1] => Array
        (
            [customer_id] => 1
            [cutomer_item] => 9
        )
// customer 2            
    [2] => Array
        (
            [customer_id] => 2
            [cutomer_item] => 3
        )

    [3] => Array
        (
            [customer_id] => 2
            [cutomer_item] => 5
        )

);

I wanto to group (csv) customers_items like:

[
// customer 1
    {
     "customer_id" : "1" // customer id preserved
     "cutomer_items" : "7,9" // customer items imploded with a comma
    }
,
// customer 2
    {
     "customer_id" : "2"
     "cutomer_items" : "3,5"
    }
]

I got confused with so many array functions (http://php.net/manual/en/ref.array.php).

Azevedo
  • 2,059
  • 6
  • 34
  • 52
  • The JSON part of your question is entirely irrelevant. Once you have properly grouped the data in a new array, just call `json_encode($grouped_array)`... – CodeCaster Jan 27 '16 at 13:44
  • Besides the `json_encode`, how can I group the customer items in a csv format? – Azevedo Jan 27 '16 at 13:46
  • 1
    Hundreds of questions about grouping exist. http://stackoverflow.com/questions/7574857/group-array-by-subarray-values – CodeCaster Jan 27 '16 at 13:46

2 Answers2

1

Here is an idea:

Code

<?php
    $my_array = array(
        array('customer_id' => 1, 'cutomer_item' => 7),
        array('customer_id' => 1, 'cutomer_item' => 9),
        array('customer_id' => 2, 'cutomer_item' => 3),
        array('customer_id' => 2, 'cutomer_item' => 7),
    );

    sort($my_array);

    $customer = '';
    $gp_array = array();
    $carr = false;
    foreach($my_array as $item) {
        if ($customer!=$item['customer_id']) {
            if ($carr!==false) {
                $carr['customer_items'] = implode(',',$carr['customer_items']);
                $gp_array[] = $carr;
            }
            $carr = array('customer_id'=>$item['customer_id'], 'customer_items' => array());
        }
        $customer = $item['customer_id'];
        $carr['customer_items'][] = $item['cutomer_item'];
    }
    if ($carr!==false) {
        $carr['customer_items'] = implode(',',$carr['customer_items']);
        $gp_array[] = $carr;
    }

    $json = json_encode($gp_array);
    echo $json
?>

Output

[{"customer_id":1,"customer_items":"7,9"},{"customer_id":2,"customer_items":"3,7"}]

hherger
  • 1,660
  • 1
  • 10
  • 13
1

You can use group_concat function in mysql query. if u are fetching the result through mysql

dev
  • 496
  • 1
  • 5
  • 18
  • it is SQLite. I'd rather handle this in the SQLite query over php. If you know how to do that in SQLite post as an answer please. – Azevedo Jan 27 '16 at 14:27