通过子阵列值分组php数组

时间:2016-01-18 15:12:29

标签: php arrays grouping

我想按子阵列的值对数组进行分组。如果我有这样的数组:

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

我想排序按照子阵列的值对这个数组进行分组,这样我就可以得到一个像这样的数组:

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

我该怎么做?

在我尝试之前:

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

问题出在propertyA上。我的结果是一个额外的属性propertyA,其表格如下:

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

1 个答案:

答案 0 :(得分:1)

以下代码应该完成这项工作。我希望这是不言自明的:

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