I'm beginner in PHP. I don't know how to precisely elaborate this question , so i will try to visualy present the problem:
This is an array i have currently:
array(
(int) 0 => array(
(int) 2015 => '2015'
),
(int) 1 => array(
(int) 2016 => '2016'
),
(int) 2 => array(
(int) 2017 => '2017'
),
(int) 3 => array(
(int) 2018 => '2018'
),
(int) 4 => array(
(int) 2019 => '2019'
),
(int) 5 => array(
(int) 2020 => '2020'
),
(int) 6 => array(
(int) 2021 => '2021'
),
(int) 7 => array(
(int) 2022 => '2022'
),
(int) 8 => array(
(int) 2023 => '2023'
)
)
I want output like this:
$array = [
2015 => '2015',
2016 => '2016'
etc..
];
Is it possible to get output like this?
CodePudding user response:
You could do simple foreach loop:
<?php
$years = array(
array(2015 => '2015'),
array(2016 => '2016'),
array(2017 => '2017'),
array(2018 => '2018'),
array(2019 => '2019'),
array(2020 => '2020'),
array(2021 => '2021'),
array(2022 => '2022'),
array(2023 => '2023')
);
foreach($years as $year) {
$key = key($year);
$value = current($year);
$result[$key] = $value;
}
var_dump($result);
Output:
$result = [
2015 => '2015',
2016 => '2016',
2017 => '2017',
2018 => '2018',
2019 => '2019',
2020 => '2020',
2021 => '2021',
2022 => '2022',
2023 => '2023'
];
CodePudding user response:
$theArray = [
[2020 => '2020'], [2021 => '2021'], [2022 => '2022'], [2023 => '2023'],
[2015 => '2015'], [2016 => '2016'], [2017 => '2017'], [2018 => '2018'], [2019 => '2019']
];
$new = [];
foreach ( $theArray as $a) {
$new[key($a)] = $a[key($a)];
}
ksort($new);
print_r($new);
RESULTS
Array
(
[2015] => 2015
[2016] => 2016
[2017] => 2017
[2018] => 2018
[2019] => 2019
[2020] => 2020
[2021] => 2021
[2022] => 2022
[2023] => 2023
)
Of course, it might be more efficient to go to the code that created your original array and amend that to create what you want rather than what it currently does.