'Convert associative array to indexed array with associative subarrays
I have a simple associative array with country data like this:
$array = array('country1' => CountryOne, 'country2' => Country Two);
How can I dynamically transform this array in a multiple array like:
array(2) {
[0] => array(2) {
["code"] => "country1", ["name"] => "CountryOne"
}
[1] => array(2) {
["code"] => "country2", ["name"] => "CountryTwo"
}
}
Solution 1:[1]
Simply loop through it and create a new array from each key/value pair.
<?php
$array = array("country1" => "CountryOne", "country2" => "CountryTwo");
$newArray = array();
foreach($array as $key => $value) {
array_push($newArray, array("code" => $key, "name" => $value));
}
var_dump($newArray);
?>
Solution 2:[2]
Simple. Iterate through your array and fill another with what you find in it :
$dst_array = array();
foreach ($array as $k => $v) {
$dst_array[] = array('code' => $k, 'name' => $v);
}
Solution 3:[3]
Foreach is the obvious way, but we can use the functional way too:
$input = array('country1' => 'CountryOne', 'country2' => 'Country Two');
$output = array_map(function($each) {
return array(
'code' => key($each),
'name' => current($each));
}, array_chunk($input, 1, true));
print_r($input);
print_r($output);
We split the associative array in chunks of 1 element and we get an array of subarrays by each key-value pair. After, we can apply a map function to adapt each pair to our needs.
Example: https://3v4l.org/9Xg6t#v8.1.4
Solution 4:[4]
This is simple do like this
$array = array( array('code'=> "country1", 'name'=> "CountryOne"), array('code'=> "country2", 'name'=> "CountryTwo"));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sarkouille |
| Solution 3 | BeardOverflow |
| Solution 4 |
