Skip to content
Advertisement

Split array with equal indices

I have a result array which is formatted like the following:

array(6) {
  [0]=>
  array(3) {
    ["company"]=>
    string(1) "A"
    ["uf_prop"]=>
    string(2) "GO"
    ["qtd_prop_uf"]=>
    string(3) "612"
  }
  [1]=>
  array(3) {
    ["company"]=>
    string(1) "A"
    ["uf_prop"]=>
    string(2) "MG"
    ["qtd_prop_uf"]=>
    string(1) "1"
  }
  [2]=>
  array(3) {
    ["company"]=>
    string(1) "A"
    ["uf_prop"]=>
    string(2) "MS"
    ["qtd_prop_uf"]=>
    string(2) "11"
  }
  [3]=>
  array(3) {
    ["company"]=>
    string(1) "A"
    ["uf_prop"]=>
    string(2) "MT"
    ["qtd_prop_uf"]=>
    string(1) "4"
  }
  [4]=>
  array(3) {
    ["company"]=>
    string(1) "A"
    ["uf_prop"]=>
    string(2) "PA"
    ["qtd_prop_uf"]=>
    string(4) "2213"
  }  
  [5]=>
  array(3) {
    ["company"]=>
    string(1) "B"
    ["uf_prop"]=>
    string(2) "PA"
    ["qtd_prop_uf"]=>
    string(1) "6"
  }
}

I want to split and organize this array like the following example if it is possible:

company: A 
uf_prop:    GO, MG, MS, MT, PA
qtd_pro_uf: 612, 1, 11, 4, 2213

company: B
uf_prop:    PA
qtd_pro_uf:  6

I wish I could divide by 2 or more if there are more companies and then show the states and the amount of a priori stores.

Advertisement

Answer

I feel the array structure is like php, so here is php solution.

$result = [];
foreach ($arr as $key => $value) {
    $result[$value['company']]['uf_prop'][]    = $value['uf_prop'];
    $result[$value['company']]['qtd_pro_uf'][] = $value['qtd_pro_uf'];
}
foreach ($result as $key => $value) {
    echo "company: " . $key . "<br/>";
    echo "uf_prop: " . implode(",", $value['uf_prop']) . "<br/>";
    echo "qtd_pro_uf: " . implode(",", $value['qtd_pro_uf']) . "<br/>";
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement