Php 多维数组中缺少索引
正如标题所示,我需要找出多维数组中缺少的索引 例如:Php 多维数组中缺少索引,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,正如标题所示,我需要找出多维数组中缺少的索引 例如: [1] => Array ( [1] => User Name [2] => empID [3] => type [4] => First Name [5] => Last Name [6] => email [7] => survey_complete [8]
[1] => Array
(
[1] => User Name
[2] => empID
[3] => type
[4] => First Name
[5] => Last Name
[6] => email
[7] => survey_complete
[8] => login_limit
[9] => multi_use
)
[2] => Array
(
[1] => fdsfdsf
[2] => 123
[3] => 1
[4] => dsdsa
[5] => dasdsad
[6] => j@j.com
[7] => xzczxcxz
[8] => czxcxz
[9] => 1
)
[3] => Array
(
[1] => dsadsada
[2] => 123
[3] => 1
[4] => dasda
[5] => dsadsadasd
[6] => j@j.com
[7] => dsdsada
[8] => dsadsadsa
[9] => 1
)
[4] => Array
(
[1] => fdsfdsf
[2] => 123
[3] => 1
[4] => dsadas
[5] => aaa
[6] => j@j.com
[7] => dsdsada
[8] => dsadsadsa
[9] => 0
)
[5] => Array
(
[1] => fdsfdsf
[2] => 123
[3] => 1
[4] => dssa
[5] => cxzcczxczxcxz
)
[7] => Array
(
[1] => MANDATORY FIELD
)
[8] => Array
(
[1] => multi_use: Enter multiuse as 0.
)
在上面的示例中,缺少索引6。有没有一种方法可以在php中找到缺少的索引(索引6)以及计算php中缺少的索引(6后有2个索引)后出现的索引数
谢谢,,
Justin只需使用array_keys()并在其中循环查找缺失的内容
array_keys($arr1);
这可能不是最好的方法,但是你可以在那里做一个例外,想法是在保存位置的同时在数组中移动,然后如果数组缺少一个索引,它将抛出和异常,你可以
echo
,或者只是返回缺少数组的位置,如果没有缺少索引,则返回-1,是这样的:
<?php
for ($x = 0; $x <= xLimit; $x++) {
for ($y = 0; $y <= yLimit; $y++) {
// Here you place the exception
try {
// Just try to enter the index to force and error if it doesn't exist
} catch (Exception $e) {
// Here you return or echo the position '(x,y)' you where when the exception ocures
}
// Else, just return something that let you know it didn't had any problem ej. '-1'
}
}
?>
希望它有用 我在下面编写的函数getMissingArrayKeys()可以为您提供缺少的索引:
<?php
function getMissingArrayKeys($arr, $ref) {
return array_diff(
array_values($ref),
array_keys($arr)
);
}
请参见下面的示例如何获取丢失的密钥
$array = array(
1 => 123,
2 => 456,
4 => 789,
8 => 789,
);
$firstkey = key($array); // get first index of array
end($array);
$lastkey = key($array); // get last index of array
for($i = $firstkey;$i <= $lastkey;$i++)
{
if(!array_key_exists($i,$array)) // check key exist or not
{
echo "Missing Array key is ".$i."<br/>";
}
}
注::-仅适用于编号索引
没有现成的解决方案,因为您需要非常具体的信息。你必须根据数组索引的简单迭代来编写你自己的函数。我不清楚“缺少索引”到底是什么意思。索引是否会在两者之间的某个位置“丢失”?第一个数组是否定义了“标准”?你到底需要什么,只是“数字N在某处缺失”,或者“数组K缺失数字N、M和J”@cdonat是的,数组从索引1开始。如示例所示,我生成的每个数组都缺少索引。我必须找到它并开始在我的代码中使用它。@Justin对不起,但你能试着回答我的问题吗?“缺失指数”到底意味着什么?
$array = array(
1 => 123,
2 => 456,
4 => 789,
8 => 789,
);
$firstkey = key($array); // get first index of array
end($array);
$lastkey = key($array); // get last index of array
for($i = $firstkey;$i <= $lastkey;$i++)
{
if(!array_key_exists($i,$array)) // check key exist or not
{
echo "Missing Array key is ".$i."<br/>";
}
}
Missing Array key is 3
Missing Array key is 5
Missing Array key is 6
Missing Array key is 7