简体   繁体   English

PHP:在数组中搜索值并显示键

[英]PHP: search for values in the array and display the key

I have array with the structure as below.我有结构如下的数组。

Array
(
    [example1] => Array
        (
            [0] => 'banana'
        )

    [example2] => Array
        (
            [0] => 'orange'
            [1] => 'apple'
            [2] => 'plum'
            [3] => 'watermelon'
            [4] => 'pumpkin'
        )

    [example3] => Array
        (
            [0] => 'cherry'
            [1] => 'strawberry'
        )

)

I am trying to display the key name for a sample value.我正在尝试显示示例值的键名。

Eg.例如。 looking for a value: ' apple ' - result: ' example2 '寻找一个值:' apple ' - 结果:' example2 '

Just iterate thru all the subarrays and return the parent key.只需遍历所有子数组并返回父键。

$array = [
    'example1' => ['banana'],
    'example2' => ['orange', 'apple', 'plum', 'watermelon', 'pumpkin'],
    'example3' => ['cherry', 'strawberry']
];

$needle = 'apple';
$result = '';
foreach($array as $parentKey => $child) {
    if(in_array($needle, $child)) {
        $result = $parentKey;
        break;
    }
}

echo $result;

example2示例2

Simply loop your arrays and check if element exists:只需循环您的 arrays 并检查元素是否存在:


function search(string $search, array $source) {
    foreach ($source as $key => $sub) {
        if (in_array($search, $sub)) {
            return $key;
        }
    }
}

search('apple', $source);

that's a good example too, thanks.这也是一个很好的例子,谢谢。 I built my function on this basis我在此基础上构建了我的 function

function CheckArray($my_array,$search) {
$result = array_keys(array_filter($my_array, function ($arr) use ($search) {
return in_array($search, $arr);
}));
if(isset($result[0])){
    return $result[0];
}else{
    return "not find";
}

} }

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

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