简体   繁体   English

搜索数组键并返回匹配键的索引

[英]Search array keys and return the index of matched key

my array looks like this: 我的数组看起来像这样:

[sx1] => Array
        (
            [sx1] => Pain in Hand
            [sx1L] => Location
            [sx1O] => Other Treat
            [sx1T] => Type
            [sx1R] => Radiation
            [sx1A] => Aggrivate Ease
            [sx1D] => Duration
            [sx1I] => Irit
            [sx1P] => Previous Hx
            [SX1T_1] => CX
            [SX1T_2] => Shld
            [SX1T_3] => Trnk
            [SX1T_4] => Hip
            [SX1T_5] => 
        )

I need to be able to search the array by a key, and then return the index of the matched item. 我需要能够通过键搜索数组,然后返回匹配项的索引。 For example, I need to search the array for the key "SX1T_1" and then return the index of that item in the array. 例如,我需要在数组中搜索键“SX1T_1”,然后返回数组中该项的索引。

Thanks for any help. 谢谢你的帮助。

You can use array_search on the array keys ( array_keys ) to get the numerical index: 您可以在数组键( array_keys )上使用array_search来获取数字索引:

$array = array(
    'sx1' => 'Pain in Hand',
    'sx1L' => 'Location',
    'sx1O' => 'Other Treat',
    'sx1T' => 'Type',
    'sx1R' => 'Radiation',
    'sx1A' => 'Aggrivate Ease',
    'sx1D' => 'Duration',
    'sx1I' => 'Irit',
    'sx1P' => 'Previous Hx',
    'SX1T_1' => 'CX',
    'SX1T_2' => 'Shld',
    'SX1T_3' => 'Trnk',
    'SX1T_4' => 'Hip',
    'SX1T_5' => '',
);
var_dump(array_search('SX1T_1', array_keys($array)));  // int(9)
$keys = array_keys($sx1);
$index = array_search('SX1T_1',$keys);

If you don't want to use any functions and need to loop through the array anyway to search or match on a specific condition (especially usefully if your searches become more complicated), then you could use the below principle to go through the array and find the index of $mykey and put it into a variable $myindex . 如果您不想使用任何函数并且需要循环遍历数组以在特定条件下搜索或匹配(特别是如果您的搜索变得更复杂),那么您可以使用以下原则来完成数组和找到$mykey的索引并将其放入变量$myindex This code assume your index starts at zero, if you want to start at 1, then initialize $index = 1; 此代码假设您的索引从零开始,如果您想从1开始,则初始化$index = 1; .

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

$index = 0;
foreach ($a as $k => $v) {
    if ($k == $mykey) {
            $myindex=$index
    }
    $index=$index+1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM