获取多维数组的索引

时间:2014-09-23 15:38:30

标签: php html arrays

我需要得到一个多维索引并将其输出为变量。我知道这很简单,但我正在努力。

例如,给出以下内容:

[1]=>
  array(11) {
    ["field_label"]=>
    string(24) "What is your first name?"
    ["field_name"]=>
    string(6) "f_name"
    ["identifier"]=>
    bool(true)
    ["options"]=>
    bool(false)
    ["form_name"]=>
    string(12) "demographics"
  }
  [2]=>
  array(11) {
    ["field_label"]=>
    string(23) "What is your last name?"
    ["field_name"]=>
    string(6) "l_name"
    ["identifier"]=>
    bool(true)
    ["options"]=>
    bool(false)
    ["form_name"]=>
    string(12) "demographics"
  }
[3]=>
  array(11) {
    ["field_label"]=>
    string(32) "Researcher who took measurements"
    ["field_name"]=>
    string(17) "weight_researcher"
    ["identifier"]=>
    bool(false)
    ["options"]=>
    bool(false)
    ["form_name"]=>
    string(6) "weight"
  }

我想找到form_name为“weight”的第一个元素的索引(#3)

2 个答案:

答案 0 :(得分:2)

只需使用foreach和if if in:

foreach($array as $key => $value) {
               //  ^ here resides the key of the parent array
    if($value['form_name'] == 'weight') { // if form name is weight
        echo $key; // echo the key
        break; // then stop on first occurence
    }
}

答案 1 :(得分:0)

array_column需要

PHP> = 5.5.0:

$key = array_search('weight', array_column($array, 'form_name'));

对于多个键:

$keys = array_keys(array_column($array, 'form_name'), 'weight');