Transform array records into another multidimensional array

Asked

Viewed 102 times

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 that (the name of the indices is irrelevant, I put there to illustrate better 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 take according to the months and year that come, take the balances of each and join them, being that always turn data sorted

1 answer

1


Taking your example and turning 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 in the following way (This is probably not the best possible algorithm, but it 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']; 
    }
}

Upshot:

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
        )

)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.