PHP array operation method solution

Source: Internet
Author: User
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] =>
)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.