简体   繁体   中英

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'
)

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 .

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
)

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
  1. Remove the uselss original keys from the input array with array_values()
  2. Group the data into 2-element subarrays
  3. Iterate the pairs 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',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM