phparraysmultidimensional-arraygroupingsub-array

Group row data of a 2d array by one column and only create a subarray of one of multiple other columns per group


I want to group an array by a subarray's value. If I have an array like this:

Array
(
    [0] => Array
        (
            [userID] => 591407753
            [propertyA] => 'text1'
            [propertyB] => 205
        )

    [1] => Array
        (
            [userID] => 989201004
            [propertyA] =>'text2'
            [propertyB] => 1407
        )

    [2] => Array
        (
            [userID] => 989201004
            [propertyA] => 'text3'
            [propertyB] => 1407
        )
)

I want to sort to group this array by a subarray's value so I can have an array like this:

Array
(
    [0]=>Array
         (
          [userID]=>59140775
          [properties]=>Array
                        (
                         [0]=>text1
                        )
          [propertyB]=>205
         )
    [1]=>Array
        (
         [userID]=>989201004
         [properties]=>Array
                          (
                           [0]=>'text2'
                           [1]=>'text3'
                          )
         [propertyB]=>1047
        )   
)

How can I make this?

Before I had tried this:

   $result = array();
        foreach ($userArray as $record)
        {
            $id=$record['userID'];
            if(isset($result[$id]))
            {
                $result[$id]['propertyA'][]=array($record['propertyA']);
            }
            else {
                  $record["propertyA"]=array($record['propertyA']);
                  unset($record['tweet']);
                  $result[$id]=$record;
                }
        }

the problem was for the propertyA. I was an the result an additional property propertyA with the table like this:

Array
(
    [0]=>Array (
        [userID]=>989201004
        [propertyA]=>'text2'
        [properties]=>Array(
            [0]=>'text2'
            [1]=>'text3'
        )
    )
)

Solution

  • The following code should do the job. I hope it is self-explanatory:

    $result = array();
    foreach ($array as $record) {
        if (!isset($result[$record['userID']])) {
            $result[$record['userID']] = array(
                'userID' => $record['userID'],
                'properties' => array($record['propertyA']),
                'propertyB' => $record['propertyB'],
            );
        }
        else {
            $result[$record['userID']]['properties'][] = $record['propertyA'];
        }
    }
    $result = array_values($result);