基于PHP中多维数组的值的FInd键[重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

以下是我使用过的数组结构

    $arr =  Array ( 
                  [0] => Array 
                  (
                        [Research] => '#00c0ef' ,
                        [class_name] => box-info 
                   )
                  [1] => Array
                  ( 
                        [Review] => '#00a65a' ,
                        [class_name] => box-success 
                    ) 
                    [2] => Array 
                    ( 
                         [Case Study] => '#3c8dbc',
                          [class_name] => box-primary 
                     ) 
        );

我想获得'#3c8dbc'的关键,这意味着我得到了作为案例研究的输出。

以下代码是否是更好的解决方案?

 $search_value = '#3c8dbc';

  $selected_array = array_filter(array_map(function ($ar) use 
 ($search_value) {return array_search($search_value,$ar);}, $userdb));

  $selected_item = reset($selected_array);
  The $selected_item will print the key of value '#3c8dbc' .

   **Output :  Case Study**
php
1个回答
0
投票
$signal = false;
for($i = 0, $l = count($userdb); $i < $l; $i++) {
    $subarray = $userdb[$i];
    foreach ($subarray as $index => $value) {
        if ($value === $myValue) {
            $key = $index;
            $signal = true;
            break;
        }
    }
    if ($signal) { break; }        
}

if (isset($key)) {
    var_dump($key);            // key name of the subarray
    var_dump($userdb[$i]);     // full subarray. $i containing the index of it in $userdb
}

这应该可以解决问题。

我用for循环遍历每个元素,这样我就可以在循环结束时保留有趣的索引。找到元素后,我离开了循环。希望能帮助到你

编辑(特定于问题中显示的数组)

// $myValue contains the input you have
if (gettype($myvalue) === "integer") {
    $key = "uid";
} else {
    if (preg_match("/^urlof/", $myValue)) {
        $key = "url";
    } else {
        $key = "name";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.