2014-09-23 161 views
-2

我需要獲取多維索引並將其輸出爲變量。我知道這很簡單,但我正在努力。獲取多維數組的索引

例如給出如下:

[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的第一個元素的索引(#3)

+1

你應該從這裏開始http://php.net/manual/en/function.array-search.php – 2014-09-23 15:40:56

回答

2

只需使用如果一個foreach和它裏面:

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

PHP> = 5.5.0需要array_column

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

對於多鍵:

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