PHP array_keys - 我做错了什么?

时间:2011-05-10 18:23:30

标签: php arrays key

我有两个数组:

$的字段名:

array(
[0] => array(
    ['fieldName'] =>'id'
    ['fieldType'] => 'int(11)'
    )
[1] =>
    ['fieldName'] =>'adminID'
    ['fieldType'] =>'int(11)'
    )
[2] =>array(
    ['fieldName'] =>'schoolID'
    ['fieldType'] =>'int(11)'
    )
[3] => array(
    ['fieldName'] =>'lessonPlanName'
    ['fieldType'] =>'varchar(255)'
    )
[4] =>array(
    ['fieldName'] =>'lessonPlanAssignmentDate'
    ['fieldType'] =>'varchar(255)'
    )
[5] =>array(
   ['fieldName'] =>'lessonPlanDueDate'
   ['fieldType'] =>'varchar(255)'
   )
[6] =>array(
   ['fieldName'] =>'lessonPlanTopics'
   ['fieldType'] =>'varchar(255)'
   )
[7] =>array(
   ['fieldName'] =>'lessonPlanDescription'
   ['fieldType'] =>'text'
   )
[8] =>array(
   ['fieldName'] =>'lessonPlanNotes'
   ['fieldType'] =>'text'
   )
)

$ formElementPairs:

array(
   ['lessonPlanName'] =>'Test'
   ['lessonPlanAssignedDate'] =>'05/11/2011'
   ['lessonPlanDueDate'] =>'05/11/2011'
   ['lessonPlanTopics'] => 1
   ['lessonPlanDescription'] =>'test'

我正在尝试检查数组2是否缺少数组1中的任何'fieldName'键,然后将它们添加到带有空条目的数组2中。以下代码的工作原理是我从第一个数组(id,adminId,schoolId等)获取“fieldName”值,但是当我使用array_keys检查第二个数组时,我得到的数组总是有一个0.还应该提到我在这个项目中使用PHP4。

//merge arrays
for($fn=0; $fn<count($fieldNames); $fn++) { 
    $thisFieldName = $fieldNames[$fn]['fieldName'];
    $fieldCheckArray = array_keys($formElementPairs, $thisFieldName);
    //$firephp->fb(count($fieldCheckArray));
}

我是否误解了array_keys和/或在PHP4中有更优雅的方法吗?

由于

2 个答案:

答案 0 :(得分:1)

您可以使用array_key_exists检查数组2是否缺少任何内容: array_key_exists

$missing = array();
for($fn=0; $fn<count($fieldNames); $fn++) { 
    $thisFieldName = $fieldNames[$fn]['fieldName'];
    if(!array_key_exists($thisFieldName, $formElementPairs)) {
        $missing[] = $thisFieldName;
    }
}
//do something with $missing

答案 1 :(得分:1)

array_keys的第二个参数是尝试匹配{em>值而不是$formElementPairs