Transform array records into another multidimensional array

0

I want to transform this array:

array:6 [
   0 => {
    "saldo": "-257,21"
    "id_mes": 1
    "ano": "2018"
  }
  1 => {
    "saldo": "-257,21"
    "id_mes": 2
    "ano": "2018"
  }
  2 => {
    "saldo": "0"
    "id_mes": 1
    "ano": "2018"
  }
  3 => {
    "saldo": "0"
    "id_mes": 2
    "ano": "2018"
  }
  4 => {
    "saldo": "-64609,14"
    "id_mes": 1
    "ano": "2018"
  }
  5 => {
    "saldo": "-64609,14"
    "id_mes": 2
    "ano": "2018"
  }
]

In this ( the name of the indices is irrelevant, I put there to better illustrate the logic ):

array:3 [
   0 => {
    "saldo_mes1_ano2018": "-257,21"
    "saldo_mes2_ano2018": "-257,21"
  }
  1 => {
    "saldo_mes1_ano2018": "0"
    "saldo_mes2_ano2018": "0"
  }
  2 => {
    "saldo_mes1_ano2018": "-64609,14"
    "saldo_mes2_ano2018": "-64609,14"
  }
]

Basically I want to pick up according to the months and years that come, pick up the balances of each one and put them together, where always the data came sorted     

asked by anonymous 16.02.2018 / 13:21

1 answer

1

Taking your example and turning it into an array called $arr :

$arr = [
   "0" => [
    "saldo" => "-257,21",
    "id_mes" => 1,
    "ano" => "2018"
  ],

  1 => [
    "saldo" => "-257,21",
    "id_mes" => 2,
    "ano" => "2018"
  ],
  2 => [
    "saldo" => "0",
    "id_mes" => 1,
    "ano" => "2018"
  ],
  3 => [
    "saldo" => "0",
    "id_mes" => 2,
    "ano" => "2018"
  ],
  4 => [
    "saldo" => "-64609,14",
    "id_mes" => 1,
    "ano" => "2018"
  ],
  5 => [
    "saldo" => "-64609,14",
    "id_mes" => 2,
    "ano" => "2018"
  ]
];

From what I understand, you can sort the way you gave as an example as follows (This is probably not the best algorithm possible but solves the problem):

$key = 0;
$meses = []; 
$newArr = []; 

foreach ($arr as $item) {
    if (!in_array($item['id_mes'], $meses)) {
        $meses[] = $item['id_mes']; 
        $newArr[$key]["saldo_mes{$item['id_mes']}_ano{$item['ano']}"] = $item['saldo']; 
    } else {
        $key++;
        $meses = [];
        $meses[] = $item['id_mes']; 
        $newArr[$key]["saldo_mes{$item['id_mes']}_ano{$item['ano']}"] = $item['saldo']; 
    }
}

Result:

Array
(
    [0] => Array
        (
            [saldo_mes1_ano2018] => -257,21
            [saldo_mes2_ano2018] => -257,21
        )

    [1] => Array
        (
            [saldo_mes1_ano2018] => 0
            [saldo_mes2_ano2018] => 0
        )

    [2] => Array
        (
            [saldo_mes1_ano2018] => -64609,14
            [saldo_mes2_ano2018] => -64609,14
        )

)
    
16.02.2018 / 22:51