Skip to content
Advertisement

How to transform this array in php? [closed]

$array1 = [
  2019 => [
    Biomasse => [summe => 32113]
    Solar => [summe => 21321]
  ]
  2020 => [
    Biomasse => [summe => 3123113]
    Solar => [summe => 21421321]
  ]
  2021 => [
    Biomasse => [summe => 2122]
    Solar => [summe => 1233]
  ]
]

I want to sort the array by the “biomasse” and “solar”. For example:

$array2 = [
    Biomasse => [summe => 32113,3123113, 2122]
    Solar => [summe => 21321, 21421321, 1233]
]
 

The “summe” should be sorted by the years.

Advertisement

Answer

Making some assumptions regarding the question here, and having my doubts about the structure of the data provided, but…

Assuming that this is the result that you want, having Biomasse and Solar sorted by Year.

$array2 = [
    Biomasse => [ valueOf2019, valueOf2020 , valueOf2021 ]
    Solar => [ valueOf2019, valueOf2020 , valueOf2021 ]
]

Then you should first do a ksort, then a foreach and then you can simply add the values to a new array.

Example;

$array1 = Array(
  "2019" => Array(
    "Biomasse" => Array( 32113 ),
    "Solar" => Array( 21321 )
  ),
  "2020" => Array(
    "Biomasse" => Array( 3123113 ),
    "Solar" => Array( 21421321 )
  ),
  "2021" => Array(
    "Biomasse" => Array( 2122 ),
    "Solar" => Array( 1233 )
  )
);

ksort( $array1 );

$array2 = Array(
    "Biomasse" => Array(),
    "Solar" => Array()
);

foreach($array1 as $year ){
        $array2["Biomasse"][] = $year["Biomasse"][0];
        $array2["Solar"][] = $year["Solar"][0];
}

echo "<pre>";
var_dump( $array2 );
echo "</pre>";
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement