2013-05-31 3 views
2

저는 PHP 세계에서오고 있습니다. 레코드 집계를해야합니다. PHP에서 나는 나에게Groovy의 연관 배열과 같은 PHP

['5-15']['foo'] = 1 
['5-15']['bar'] = 1 
['5-16']['foo'] = 1 
['5-17']['foo'] = 2 
['5-17']['bar'] = 2 

로그 실제로 GORM 쿼리에서 반환 된 내 결과 집합은 결과를 제공

$logs = array(array('date' => '5-15', 'name' => 'foo' ...other stuff), 
       array('date' => '5-15', 'name' => 'bar' ...other stuff), 
       array('date' => '5-16', 'name' => 'foo' ...other stuff), 
       array('date' => '5-17', 'name' => 'foo' ...other stuff), 
       array('date' => '5-17', 'name' => 'foo' ...other stuff), 
       array('date' => '5-17', 'name' => 'bar' ...other stuff), 
       array('date' => '5-17', 'name' => 'bar' ...other stuff)); 

$counts = array(); 

foreach($logs as $log) { 
    if(isset($counts[ $log['date'] ][ $log['name'] ])) { 
     $counts[ $log['date'] ][ $log['name'] ] = 1; 
    } else { 
     $counts[ $log['date'] ][ $log['name'] ]++; 
    } 
} 

그루비

에서 다음이 간단 알고 있지만 어떻게합니까.

답변

4

Groovy countBy을 사용할 수 있습니다.

def map = logs.countBy{[it.date, it.name]}

당신은 결과의지도 및 해당 수를 끝낼 것입니다. 당신이지도에서 <key,value>each을 얻을 필요가있는 경우

def logs = [ 
     [ date: '5-15', name: 'foo'], 
     [ date: '5-15', name: 'bar'], 
     [ date: '5-16', name: 'foo'], 
     [ date: '5-17', name: 'foo'], 
     [ date: '5-17', name: 'foo'], 
     [ date: '5-17', name: 'bar'], 
     [ date: '5-17', name: 'bar']] 

def map = logs.countBy{[it.date, it.name]} 

assert map[['5-15', 'foo']] == 1 
assert map[['5-15', 'bar']] == 1 
assert map[['5-16', 'foo']] == 1 
assert map[['5-17', 'foo']] == 2 
assert map[['5-17', 'bar']] == 2 

샘플

[[5-15, foo]:1, [5-15, bar]:1, [5-16, foo]:1, [5-17, foo]:2, [5-17, bar]:2]

같이 귀하의 경우가 될 것입니다. 같은 당신은 잘 할 수 있습니다 : -

map.each{k, v -> 
    println "$k has been used $v times" 
} 

//Prints: 
[5-15, foo] has been used 1 times 
[5-15, bar] has been used 1 times 
[5-16, foo] has been used 1 times 
[5-17, foo] has been used 2 times 
[5-17, bar] has been used 2 times 
는 그루비 2.1.3

+0

시험이 내가하려고 할 때 작동하고 때 나는 예상대로 정확히 모든 값을 포함하는 객체를 인쇄 로그 디버깅하지만, 지도에서 특정 값을 얻으려면 NULL이 표시됩니다. –

+0

@BDKosher가 사용했던 나의 친애하는 친구와 동일한 주장을 시도해보십시오. 내 업데이 트를 참조하십시오. – dmahapatro

+0

@MikeLP 잘 보입니까? – dmahapatro

2

이것은 카운트 맵에서 복합 키를 사용하고 있습니다. 그래도 다른 방법으로 슬라이스 앤 다이스 할 수 있습니다.

def logs = [ 
     [ date: '5-15', name: 'foo'], 
     [ date: '5-15', name: 'bar'], 
     [ date: '5-16', name: 'foo'], 
     [ date: '5-17', name: 'foo'], 
     [ date: '5-17', name: 'foo'], 
     [ date: '5-17', name: 'bar'], 
     [ date: '5-17', name: 'bar']] 

def counts = [:]   
logs.collectEntries(counts) { 
    def key = [it.date, it.name] 
    def count = counts[key] ?: 0 
    [key, count + 1] 
} 


assert counts[['5-15', 'foo']] == 1 
assert counts[['5-15', 'bar']] == 1 
assert counts[['5-16', 'foo']] == 1 
assert counts[['5-17', 'foo']] == 2 
assert counts[['5-17', 'bar']] == 2