说我有这样的数组:
$chartData = array ( [00] => 1 [03] => 1 [09] => 1 [10] => 3 [11] => 1 [12] => 4 [13] => 2 [14] => 4 [15] => 6 [16] => 3 [17] => 5 [18] => 2 [20] => 1 [22] => 1 ) 1
如何填写缺失的索引直至24(02,04,05,等等,直到24)0?
答案 0 :(得分:0)
您可以尝试这样的事情
function addkeyforArray(&$array)
{
end($array);
$maxcount = key($array); //Get the final key as max!
for($i = 01; $i < $maxcount; $i++)
{
if(!isset($array[$i]))
{
$array[$i] = '';
}
}
}
addkeyforArray($array);
答案 1 :(得分:0)
最简单的方法是双线循环。
for ($i = min($k=array_keys($chartData)); $i<=max($k); $i++)
$chartData[$i] = isset($chartData[$i]) ? $chartData[$i] : 0;
答案 2 :(得分:-1)
我会得到键列表,使用它来创建期望的键列表,然后在数组上执行diff。就这样
//Get the keys
$keys = array_keys($chartData);
//Convert them to integers for easier use
$keys = array_map(function ($key) {
return (int) $key;
}, $keys);
//Get the last key
end($keys);
$lastKey = current($keys);
//Create the keys that we expect
$expectedKeys = range(0, $lastKey);
//Find out which keys are missing
$missingKeys = array_diff($expectedKeys, $keys);