Php创建具有关联值和计数的数组

时间:2014-07-01 09:21:24

标签: php arrays

我有一个具有这种结构的数组

Array
(
    [0] => Array
        (
            [profileId] => 1000000407
            [locationId] => 207

        )

    [1] => Array
        (
            [profileId] => 1000000407
            [locationId] => 250

        )

    [2] => Array
        (
            [profileId] => 1000000398
            [locationId] => 250

        )

    [3] => Array
        (
            [profileId] => 1000000393
            [locationId] => 250

        )
    [4] => Array
            (
             [profileId] => 1000000393
             [locationId] => 250

            )
)

从这个数组我想创建一个新的数组,其中Ids作为键的位置,并且该数组包含与该位置相关联的profileId的计数。 所以在这个例子中我需要返回

Array
(
   [207] => Array
        (
         [1000000407] => 1
        )
   [250] => Array
        (
         [1000000407] => 1
         [1000000398] => 1
         [1000000393] => 2
        )
)

我很欣赏这可能很简单,但我似乎无法绕过它。

3 个答案:

答案 0 :(得分:6)

我通常使用array_reduce来执行这些任务,如下所示:

$new = array_reduce(
     $old,
     function($result, $item) 
     {
         $result[$item['locationId']][$item['profileId']] += 1;
         return $result;
     }
)

答案 1 :(得分:1)

解决方案是......

$main = array(
    array(
            'profileId' => 1000000407,
            'locationId' => 207

        ),

    array(
            'profileId' => 1000000407,
            'locationId' => 250

        ),

    array(
            'profileId' => 1000000398,
            'locationId' => 250

        ),

    array(
            'profileId' => 1000000393,
            'locationId' => 250

        ),
    array(
             'profileId' => 1000000393,
             'locationId' => 250

            )
);

$output = array();

foreach ($main as $node)
{
    if ( ! isset($output[$node['locationId']]))
    {
        $output[$node['locationId']] = array();
    }

    if ( ! isset($output[$node['locationId']][$node['profileId']]))
    {
        $output[$node['locationId']][$node['profileId']] = 1;
    }
    else
    {
        $output[$node['locationId']][$node['profileId']]++;
    }
}

print_r($output);

答案 2 :(得分:1)

这可能会做你想要的事情

$locationId = '';
$counter = 1;
$new_arr = array();
$profileId = '';
foreach($my_arr as $row)
{
    if($row['locationId'] != $locationId)
    {
        $locationId = $row['locationId'];
        $profileId = $row['profileId'];
        $new_arr[$row['locationId']] = array($row['profileId'] => $counter);
    }
    else
    {
        if($row['profileId'] != $profileId)
        {
           $profileId = $row['profileId'];
           $counter = 1;
        }
        else
        {
           $counter++;
        }
        $new_arr[$row['locationId']][$row['profileId']] = $counter;
    }
}