简体   繁体   中英

How to convert a 1-dimensional array into a 2-dimensional array in PHP

I have an array as follows:

$array['a'] = 'Red';
$array['b'] = 'Green';
$array['c'] = 'Blue';

I want to convert it to:

$array['a'][1] = 'Red';
$array['b'][1] = 'Green';
$array['c'][1] = 'Blue';

Is that possible with an existing PHP function or do I need to write my own function?

No, there is no built-in function that can achieve this. However, this is pretty straight-forward with a foreach loop, so I don't see why you need a function:

$result = array();

foreach ($array as $key => $value) {
    $result[$key][1] = $value;
}

print_r($result);

If you want a more functional approach, you could use array_walk() :

// walks through the original $array and adds a new dimension
array_walk($array, function(&$v, $k){ 
    $v = array(1 => $v); 
});

Although, a normal foreach would be more straight-forward and readable.

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