'Convert every two values of an associative array into key-value pairs
I need to convert an associative array into a new associative array where the original keys are ignored and every two consecutive values become new key-value pairs.
Input:
Array
(
[SELECT0] => 'orange'
[INPUT0] => '100'
[SELECT1] => 'bannana'
[INPUT1] => '200'
[SELECT2] => 'apple'
[INPUT2] => '300'
)
Desired output:
Array
(
[orange] => '100'
[bannana] => '200'
[apple] => '300'
)
Solution 1:[1]
Here is one way combining three PHP array functions:
$result = array_combine(...array_map(null, ...array_chunk($array, 2)));
array_chunk
gives you
[
['orange', '100'],
['banana', '200'],
['apple', '300']
];
array_map
converts that to:
[
['orange', 'banana', 'apple'],
['100', '200', '300'],
];
Which can feed directly into array_column
.
Solution 2:[2]
All you need to do, is loop over all you array values and then take every odd one as key and the next index as value.
$arr = [
'SELECT0' => 'orange',
'INPUT0' => '100',
'SELECT1' => 'bannana',
'INPUT1' => '200',
'SELECT2' => 'apple',
'INPUT2' => '300'
];
$arr = array_values($arr);
$newData = [];
for ($i = 0; $i < count($arr); $i++) {
$newData[$arr[$i]] = $arr[++$i];
}
Now $newData
contains this:
Array
(
[orange] => 100
[bannana] => 200
[apple] => 300
)
Solution 3:[3]
assuming the format will never change ...
$new=array();//start a new array
$count=count($array)/2; //get the number of items to loop through
for ($i = 0; $i < $count; $i++) { //loop
$k='SELECT'.$i; //key
$v='INPUT'.$i; //value
$new[$array[$k]]=$array[$v]; //create new array
}
print_r($new); //display
Solution 4:[4]
- Remove the uselss original keys from the input array with
array_values()
- Group the data into 2-element subarrays
- Iterate the paris and use "array destructuring" to temporarily declare the
$newKey
and then push the related value into the result array using$newKey
. The foreach's body is not required.
Code: (Demo)
$result = [];
foreach (array_chunk(array_values($arr), 2) as [$newKey, $result[$newKey]]);
var_export($result);
Output:
array (
'orange' => '100',
'bannana' => '200',
'apple' => '300',
)
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 | Manuel Mannhardt |
Solution 3 | |
Solution 4 | mickmackusa |