repl.it
@IsraelMerljak/

StckOvrFlwArrayToMap

PHP (Legacy)

Resposta pergunta stackoverflow: https://pt.stackoverflow.com/questions/322090/agrupar-valor-de-um-array-em-php

fork
loading
main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
$input = [
	(object) [
		"anomes" => 201601,
        "codreg" => 41,
        "nomreg" => "PR",
        "codcin" => 1,
        "nomcin" => "OUTROS",
        "valven" => 6835.7000,
        "qtdven" => 1078.8000
		],
	(object) [
		"anomes" => 201601,
        "codreg" => 42,
        "nomreg" => "SC",
        "codcin" => 1,
        "nomcin" => "OUTROS",
        "valven" => 3129.0000,
        "qtdven" => 366.6200
		],
	(object) [
		"anomes" => 201601,
        "codreg" => 42,
        "nomreg" => "SC",
        "codcin" => 2,
        "nomcin" => "PECAS",
        "valven" => 346.9100,
        "qtdven" => 73.6600
		],
	
	];

// OPÇÃO 1
function groupByCodReg($inputArray) {
	$resultMap = [];
	
	foreach($inputArray as $data) {
		if(!isset($resultMap[$data->codreg])) {
			$resultMap[$data->codreg] = [];	
		}
		
		$resultMap[$data->codreg][] = $data;	
	}
	
	return $resultMap;
}
// FIM OPÇÃO 1

// OPÇÃO 2
function aggregateValvenByNomreg($inputArray) {
  $resultMap = [];

  foreach($inputArray as $data) {
    if(!isset($resultMap[$data->nomreg])) {
      $resultMap[$data->nomreg] = [];
    }

    $resultMap[$data->nomreg][] = $data->valven;
  }

  // completa arrays com 0
  $maiorComprimento = getLengthier($resultMap);
  foreach($resultMap as $key => $value) {
    $resultMap[$key] = array_pad($resultMap[$key], $maiorComprimento, 0.0);
    // while(count($resultMap[$key]) < $maiorComprimento) {
    //   $resultMap[$key][] = 0.0;
    // }
  }

  return $resultMap;
}

function getLengthier($array) {
  $max = 0;

  foreach($array as $data) {
    $length = count($data);
    if($length > $max) $max = $length;
  }

  return $max;
}
// FIM OPÇÃO 2

//TESTANDO OPÇÃO 1
echo "============= Opção 1\n";
var_dump(groupByCodReg($input));

// TESTANDO OPÇÃO 2
echo "\n\n============= Opção 2\n";
var_dump(aggregateValvenByNomreg($input));
PHP 7.0.8 (Legacy: use the following for new features: Command-line PHP: https://repl.it/languages/php_cli PHP Web Server: https://repl.it/languages/php7
?