2014-04-14 3 views
0

배열에 배열 값이 +1 인 경우 목록을 생성하고 싶습니다.PHP가 배열 내부에서 계산하기

전류 출력 내가 무엇을 달성하고자하는

[1] => Array 
    (
     [source] => 397 
     [value] => 1 
    ) 

[2] => Array 
    (
     [source] => 397 
     [value] => 1 
    ) 

[3] => Array 
    (
     [source] => 1314 
     [value] => 1 
    ) 

[1] => Array 
    (
     [source] => 397 
     [value] => 2 
    ) 

[2] => Array 
    (
     [source] => 1314 
     [value] => 1 
    ) 

나의 현재 아래 무디게 PHP

 foreach ($submissions as $timefix) { 

       //Start countng 
       $data = array(
        'source' => $timefix['parent']['id'], 
        'value' => '1' 
      ); 

       $dataJson[] = $data; 

    } 

      print_r($dataJson); 

답변

2

단순히 관련 배열을 사용 배열 키는 보존되지 않지만 적합하면 항목 ID를 배열 키로 사용할 수 있습니다. 이렇게하면 이미 사용 가능한 결과를 반복 할 필요가 없도록 코드를 단순화 할 수 있습니다.

foreach ($submissions as $timefix) { 
    $id = $timefix['parent']['id']; 
    if (array_key_exists($id, $dataJson)) { 
     $dataJson[$id]["value"]++; 
    } else { 
     $dataJson[$id] = [ 
      "source" => $id, 
      "value" => 1 
     ]; 
    } 
} 
print_r($dataJson); 
+1

감사의 말로는이 솔루션이 가장 좋은 것 같습니다. – Brent

0

PHP에는 array_count_values이라는 함수가 있습니다. 당신이 그것을 사용할 수 있습니다 될 수 있습니다

예 :

<?php 
$array = array(1, "hello", 1, "world", "hello"); 
print_r(array_count_values($array)); 
?> 

출력 :

$dataJson = array(); 

foreach ($submissions as $timefix) { 
    $id = $timefix['parent']['id']; 

    if (!isset($dataJson[$id])) { 
     $dataJson[$id] = array('source' => $id, 'value' => 1); 
    } else { 
     $dataJson[$id]['value']++; 
    } 
} 

$dataJson = array_values($dataJson); // reset the keys - you don't nessesarily need this 
+0

내 예제에서는 어떻게 작동합니까? – Brent

1

이 정확히 원하는 출력과 같이이다 :

Array 
(
    [1] => 2 
    [hello] => 2 
    [world] => 1 
) 
0

사용자가 직접 간소화해야합니다. 뭔가 같이 :이 후

<? 
    $res = Array(); 
    foreach ($original as $item) { 
    if (!isset($res[$item['source']])) $res[$item['source']] = $item['value']; 
    else $res[$item['source']] += $item['value']; 
    } 
?> 

, 당신이 뭔가를 할 것이다 배열 $res해야합니다 :

: 당신이 정말로 지정된 형식을 필요로하는 경우

Array(
    [397] => 2, 
    [1314] => 1 
) 

다음을, 당신은 같은 것을 사용할 수 있습니다

<? 
    $final = Array(); 
    foreach ($res as $source=>$value) $final[] = Array(
    'source' => $source, 
    'value' => $value 
); 
?> 
0

이 코드는 예제에서 설명한대로 카운트를하고 $new 배열을 생성합니다.

$data = array(
    array('source' => 397, 'value' => 1), 
    array('source' => 397, 'value' => 1), 
    array('source' => 1314, 'value' => 1), 
); 

$new = array(); 
foreach ($data as $item) 
{ 
    $source = $item['source']; 
    if (isset($new[$source])) 
     $new[$source]['value'] += $item['value']; 
    else 
     $new[$source] = $item; 
} 
$new = array_values($new);