标签:
今天在CSDN上,看到了一个问题
一维数组
array(‘a‘=>‘b‘,‘c‘=>‘d‘,‘e‘=>‘f‘);
这样子,就是第一个值作为key,第二个值作为value,以此类推,,不足偶数个,最后一个为NULL
一个很好的解决办法:
$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]] = ! empty ( $t [1] ) ? $t [1] : null; } var_dump ( $b );
重点说下array_chunk() 函数,array_chunk() 函数把一个数组分割为新的数组块。
<?php $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow"); print_r(array_chunk($a,2)); ?>
输出:
Array ( [0] => Array ( [0] => Cat [1] => Dog ) [1] => Array ( [0] => Horse [1] => Cow ) )
<?php $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow"); print_r(array_chunk($a,2,true)); ?>
输出:
Array ( [0] => Array ( [a] => Cat [b] => Dog ) [1] => Array ( [c] => Horse [d] => Cow ) )
很容易发现,第三个参数的作用,,如果在做某些项目时,需要将KEY 重新归0,可以快速的形成
标签:
原文地址:http://www.cnblogs.com/Mwsoft/p/4335268.html