PHP array operation method to solve one-dimensional array (0 & gt; a, 1 & gt; B, 2 & gt; c, 3 & gt; d, 4 & gt; e, 5 & gt; f); it may take a long time. I want to convert it to array (a & gt; B, c & gt; d, e & gt; f, that is, the first value is the key, the second value is the value, and so on. Evaluate the method! --- PHP array operation method
One-dimensional array
array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f');
It may be long
I want to convert
array('a'=>'b','c'=>'d','e'=>'f');
In this way, the first value is used as the key, the second value as the value, and so on. Evaluate the method!
------ Solution ----------------------
If you do this, you must ensure that your data must be an even number. Otherwise, there must be incomplete data. When your data is an even number, you can traverse it.
$arr = array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f','6'=>'g','7'=>'h');
$i = 0;
$len = count($arr);
$newArr = array();
while($i < $len){
$newArr[$arr[$i]] = $arr[$i+1];
$i += 2;
}
var_dump($newArr);
?>
------ Solution ----------------------
Change the upstairs slightly .. In this way, you can skip the parity.
$arr = array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f','6'=>'g','7'=>'h','8'=>'i');
$i = 0;
$len = count($arr);
$newArr = array();
while($i < $len){
$newArr[$arr[$i]] = array_key_exists($i+1,$arr)?$arr[$i+1]:null;
$i += 2;
}
var_dump($newArr);
?>
------ Solution ----------------------
$a = array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f', 'G');
foreach(array_chunk($a, 2) as $t) {
$b[$t[0]] = @$t[1];
}
print_r($b);
Array
(
[a] => b
[c] => d
[e] => f
[G] =>
)