簡體   English   中英

PHP創建具有關聯值和計數的數組

[英]Php create array with associative values and count

我有一個具有這種結構的數組

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

我很欣賞這可能很簡單,但是我似乎無法解決這個問題。

我通常將array_reduce用於這些任務,如下所示:

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

解決方法是...

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

這可能會做你想要的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM