如何在不使用foreach的情况下比较数组键

时间:2011-10-14 19:19:43

标签: php

我有一个多维数组$finalUserElearningLesson。我想做的是将其键与另一个数组的键进行比较。 if($finalUserElearningLesson[$i][$field] == $field)实际上并不比较密钥而是值。如何比较密钥?

for($i=0;$i<count($finalUserElearningLesson);$i++) {
$uFields = array();
foreach($fields as $field) {
  if($finalUserElearningLesson[$i][$field] == $field){
    $uFields[$field] = $finalUserElearningLesson[$i][$field];
  }
}

fputcsv($output, $uFields);  
}    

2 个答案:

答案 0 :(得分:0)

函数array_keys将为您的数组提供一系列键,这对您有帮助吗?

答案 1 :(得分:0)

如果我在此之后了解你的情况,那么这可能更符合正确的方向。对于$finalUserElearningLesson中的每一行,它将输出同时存在于$fields中的字段(键)。

$fields = array('field1' => 'value1', 'field2' => 'value2', 'field4' => 'value4');
$fieldsKeys = array_keys($fields);

$finalUserElearningLesson[0] = array('field1' => 'value1',
                                     'field2' => 'value2',  
                                     'field3' => 'value3');
$finalUserElearningLesson[1] = array('field2' => 'value2',  
                                     'field3' => 'value3');
$finalUserElearningLesson[2] = array('field1' => 'value1',
                                     'field3' => 'value3',
                                     'field4' => 'value4');

for($i=0;$i<count($finalUserElearningLesson);$i++) {

    // annoyingly array_intersect_key() returns values, not keys

    // get the keys in $finalUserElearningLesson[$i]
    $lessonKeys = array_keys($finalUserElearningLesson[$i]);

    // get the keys that exist in $finalUserElearningLesson[$i]
    // and $fields
    $keysInBoth = array_intersect($fieldsKeys, $lessonKeys);

    echo "Keys in row $i: ", implode(',', $keysInBoth), "\n";
}

将输出:

Keys in row 0: field1,field2
Keys in row 1: field2
Keys in row 2: field1,field4