Home > Backend Development > PHP Tutorial > PHP 一个数组操作方法求解解决方案

PHP 一个数组操作方法求解解决方案

WBOY
Release: 2016-06-13 12:18:32
Original
955 people have browsed it

PHP 一个数组操作方法求解
一维数组

<br />array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f');<br />
Copy after login

可能很长

我想转成
<br />array('a'=>'b','c'=>'d','e'=>'f');<br />
Copy after login

这样子,就是第一个值作为key,第二个值作为value,以此类推,求方法!
------解决思路----------------------
楼主你这样做,就要保证你的数据必须是偶数的,不然最后肯定有不完整。当你数据是偶数时,就可以进行遍历
<br /><?php <br />$arr = array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f','6'=>'g','7'=>'h');<br />$i = 0;<br />$len = count($arr);<br />$newArr = array();<br />while($i < $len){<br />	$newArr[$arr[$i]] = $arr[$i+1];<br />	$i += 2;<br />}<br />var_dump($newArr);<br />?> <br />
Copy after login

------解决思路----------------------
把楼上的稍微改了下。。 这样应该就可以了 不用管奇偶数了
<br /><?php <br />$arr = array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f','6'=>'g','7'=>'h','8'=>'i');<br />$i = 0;<br />$len = count($arr);<br />$newArr = array();<br />while($i < $len){<br />    $newArr[$arr[$i]] = array_key_exists($i+1,$arr)?$arr[$i+1]:null;<br />    $i += 2;<br />}<br />var_dump($newArr);<br />?> <br />
Copy after login

------解决思路----------------------
$a = array('0'=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f', 'G');<br />foreach(array_chunk($a, 2) as $t) {<br />  $b[$t[0]] = @$t[1];<br />}<br />print_r($b);<br /><br />
Copy after login
Array<br />(<br />    [a] => b<br />    [c] => d<br />    [e] => f<br />    [G] => <br />)<br /><br />
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template