2011-05-10 72 views
4

我有兩個數組:PHP array_keys - 我做錯了什麼?

$字段名:

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?

感謝

回答

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 
+0

我會嘗試,但任何想法爲什麼array_keys不會按照我使用它的方式工作? – PruitIgoe 2011-05-10 18:33:16

+0

@pruitigoe'array_keys'返回爲傳遞的**值**找到的鍵的數組。查看[文檔](http://php.net/manual/en/function.array-keys.php) – 2011-05-10 18:50:40

1

的第二個參數array_keys試圖匹配而不是$formElementPairs

+0

看看這個例子(第二個)在w3schools:
<?php $ a = array(「a 「=>」 馬」, 「b」=> 「貓」, 「C」=> 「狗」); print_r(array_keys($ a,「Dog」)); ?>
http://www.w3schools.com/php/func_array_keys.asp – PruitIgoe 2011-05-11 13:59:58

+0

看看這個例子(第二個)在w3schools:'<?php $ a = array(「a」=>「Horse」, 「b」=> 「貓」, 「C」=> 「狗」); print_r(array_keys($ a,「Dog」)); ?>結果將是Array([0] => c)通過檢查一個鍵的值是不是獲得匹配結果? [w3school](http://www.w3schools.com/php/func_array_keys.asp) – PruitIgoe 2011-05-11 14:06:30