在php中用空字符串填充数组的中间索引
我正在通过php代码阅读excel表格。有些字段是可选的。当我使用这个库时,我得到的结果是这样的在php中用空字符串填充数组的中间索引,php,arrays,Php,Arrays,我正在通过php代码阅读excel表格。有些字段是可选的。当我使用这个库时,我得到的结果是这样的 Array ( [1] => Test123 [2] => None [3] => Booster [6] => Yes [7] => Yes [8] => 1 [9] => Unknown [10] => 21 [11] => http://unknowm.com
Array
(
[1] => Test123
[2] => None
[3] => Booster
[6] => Yes
[7] => Yes
[8] => 1
[9] => Unknown
[10] => 21
[11] => http://unknowm.com
)
您可以看到索引4和5缺失,因为excel文件列中不存在这些值。现在我必须将这个数组与另一个具有命名索引的数组合并。第二个数组的长度是11。但是当我合并两者时,会产生一个php错误,即未定义索引4和5。我在动态地做这项工作,我不得不使用第二个数组的所有索引。我将缺少的第一个(来自excel)数组索引在mergin之前填充为空字符串,然后再填充到第二个数组索引。我该怎么做?我希望我已经提供了很多信息。您可以使用创建一个数组,其中包含希望结果具有的所有键,并使用数组加法运算符添加原始数组中缺少的键:
$firstIndexToEnsure = 1;
$lastIndexToEnsure = 11;
$defaults = array_fill($firstIndexToEnsure,
$lastIndexToEnsure - $firstIndexToEnsure + 1,
'');
$array += $defaults;
如果需要按键对结果进行额外排序,则还可以对其使用ksort
值得一提的是,无论您接受的用户输入可能仅部分覆盖某些默认值,此技术也适用于非整数键:
$params = array('color' => 'blue', 'size' => 'large');
$defaults = array(
'color' => 'red',
'size' => 'large',
'shape' => 'square',
'age' => 'old',
);
$params += $defaults;
试着这样做:
$array = array(
0 => "a",
2 => "b",
4 => "b",
5 => "b",
6 => "b",
);
// If min and max are static, use numbers instead of getting them from the array
$keys = array_keys($array);
$all = array_fill(min($keys), max($keys) - min($keys) + 1, "");
$filled = $array + $all;
var_dump($filled);
完成第一个阵列:
$lastindex = 11;
for($i=1; $i<=$lastindex; $i++)
if( !isset($array[$i] ))
$array[$i] = '';
$lastindex=11;
对于($i=1;$i您的最终目标是什么?为什么要合并这两个数组?您能从excel中获得一个assoc数组,而不是有间隙的普通数组吗?我必须将其插入数据库,并且我不想在每个数组索引上使用isset。您使用哪个库读取excel?您如何读取excel?感谢此解决方案。GreatThank对于最简单的解决方案,我仍然希望避免循环,Jon的是最好的