简体   繁体   中英

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.

Thanks for any help.

You can use array_search on the array keys ( array_keys ) to get the numerical index:

$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 . This code assume your index starts at zero, if you want to start at 1, then initialize $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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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