Home > OS >  Recomposing an array in PHP
Recomposing an array in PHP

Time:12-10

I have this array that needs to be converted or recomposed to form a new array.

The original array is this below

Array
(
    [0] => Array
        (
            [amount] => 1439.53
            [c_year] => 2021
            [c_month] => 9
            [short_month] => Sep
        )

    [1] => Array
        (
            [amount] => 1448.13
            [c_year] => 2021
            [c_month] => 10
            [short_month] => Oct
        )

)

Note: month = [c_month].'-'.[c_year]

I need it to to look like the below array

Array
(
    [0] => Array
        (
          [month] => Sept-9
          [amount] => 1439.53
         )
    [1] => Array
        (
          [month] => Oct-9
          [amount] => 1448.13
        )
)

I have tried a few loops but appear unable to convert or recompose it.

My efforts are listed below.

```
foreach ($resultsArray as $key=>$value) {
    $monthsFees = array('month'=>$value['c_year'].'-'.$value['c_month']);array('amount'=>$value['amount']);

    }
```

Result:

Array
(
    [month] => 2021-10
)


```
foreach ($resultsArray as $key=>$value) {
    array_push($monthsFees,'amount',$value['amount'],'month' ,$value['short_month'].'-'.$value['c_year']);
    }
```

Result:

Array
(
    [0] => amount
    [1] => 1439.53
    [2] => month
    [3] => Sep-2021
    [4] => amount
    [5] => 1448.13
    [6] => month
    [7] => Oct-2021
)


```
$feesLast6MonthsArray['month']= $value['c_year'].'-'.$value['c_month'];
      $feesLast6MonthsArray['amount']=$value['amount'];
}
```

Result:

Array
(
    [month] => 2021-10
    [amount] => 1448.13
)

CodePudding user response:

You can use array_map() to transform the array to what you want

$monthsFees = array_map(function($fee) {
    return [
        "month"  => sprintf("%s-%s",
             $fee["c_month"], 
             $fee["c_year"]
        ), // [c_month].'-'.[c_year]
        "amount" => $fee["amount"]
    ];
}, $resultsArray);

Demo ~ https://3v4l.org/0trIY

  • Related