Home > Backend Development > PHP Tutorial > php 给一个有序数组 空的key赋值

php 给一个有序数组 空的key赋值

WBOY
Release: 2016-06-23 13:05:27
Original
1188 people have browsed it

有一个数组=>

$arr = array(	        '0' => 'a value',	        '1' => 'a value',	        '2' => 'a value',	        '4' => 'a value',	        '5' => 'a value',	        '7' => 'a value',	        '10' => 'a value',	        '11' => 'a value',	        '12' => 'a value',	    );
Copy after login

同时,我有一个
$num
Copy after login

假定
$num=15
Copy after login


此时,我想得到这个数组=>
$arr = array(	        '0' => 'a value',	        '1' => 'a value',	        '2' => 'a value',	        '3' => 'kong',	        '4' => 'a value',	        '5' => 'a value',	        '6' => 'kong',	        '7' => 'a value',	        '8' => 'kong',	        '9' => 'kong',	        '10' => 'a value',	        '11' => 'a value',	        '12' => 'a value',	        '13' => 'kong',	        '14' => 'kong',	        '15' => 'kong',	    );
Copy after login



请问有什么便捷、快速的方法,生成这个数组


回复讨论(解决方案)

$arr = array(	'0' => 'a value',	'1' => 'a value',	'2' => 'a value',	'4' => 'a value',	'5' => 'a value',	'7' => 'a value',	'10' => 'a value',	'11' => 'a value',	'12' => 'a value',);$num=15;$tmp = range(0,$num);$keys = array_keys($arr);$kongArr = array_fill_keys(array_diff($tmp,$keys),'kong');//因为是数字索引,若使用 array_merge 会重新索引,不能排序foreach($kongArr as $k=>$v){	$arr[$k] = $v;}ksort($arr);echo "<pre class="brush:php;toolbar:false">";print_r($arr);echo "
Copy after login
";/*Array( [0] => a value [1] => a value [2] => a value [3] => kong [4] => a value [5] => a value [6] => kong [7] => a value [8] => kong [9] => kong [10] => a value [11] => a value [12] => a value [13] => kong [14] => kong [15] => kong)*/

没那么复杂

$arr = array(  '0' => 'a value',  '1' => 'a value',  '2' => 'a value',  '4' => 'a value',  '5' => 'a value',  '7' => 'a value',  '10' => 'a value',  '11' => 'a value',  '12' => 'a value',);$num = 15;$b = $arr + array_fill(0, $num+1, 'kong');ksort($b);print_r($b);
Copy after login
Array(    [0] => a value    [1] => a value    [2] => a value    [3] => kong    [4] => a value    [5] => a value    [6] => kong    [7] => a value    [8] => kong    [9] => kong    [10] => a value    [11] => a value    [12] => a value    [13] => kong    [14] => kong    [15] => kong)
Copy after login

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