欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-19 10:30:48
...
有一个数组=>
$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

假定
$num=15


此时,我想得到这个数组=>
$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',	    );



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


回复讨论(解决方案)

$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 "
";print_r($arr);echo "
";/*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);
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)