我正在尝试获取嵌套数组所有列中的多维数组索引。示例:
$array =
[
"int" => [80,85,66],
"text" => [57,58],
"varchar" => [82,72,70],
"decimal" => [60,61]
];
我想在php中搜索一个函数(组合)以像这样从Id获取tpye:
以61返回“ deicmal”(索引) 用58返回“文本”
但仅与数组 php核心功能结合使用,没有for循环
答案 0 :(得分:3)
我不确定您想要什么,但是您可以检查以下解决方案:
<?php
$array =
[
"int" => [80,85,66],
"text" => [57,58],
"varchar" => [82,72,70],
"decimal" => [60,61]
];
getTypeFromId(61, $array);
function getTypeFromId($index, $array) {
foreach ($array as $k => $v) {
if (in_array($index, $v)) {
echo "With " . $index . " return " . $k;
}
}
}
结果:
With 61 return decimal
答案 1 :(得分:2)
参考php文档link中的注释。
$array =
[
"int" => [80,85,66],
"text" => [57,58],
"varchar" => [82,72,70],
"decimal" => [60,61]
];
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
echo recursive_array_search(61,$array); // decimal
echo recursive_array_search(58,$array); // text
答案 2 :(得分:1)
在这里,我们将原始数组过滤为仅包含包含所需数字的数组。然后,我们只获取剩下的那个元素的密钥。 (假设您所有的电话号码都是唯一的。)
[:foo, :bar]
输出:
<?php
$array =
[
"int" => [80,85,66],
"text" => [57,58],
"varchar" => [82,72,70],
"decimal" => [60,61]
];
$target = 70;
$filtered = array_filter($array, function($v) use ($target) {
return in_array($target, $v);
});
echo key($filtered);
答案 3 :(得分:0)
如果您不喜欢foreach,则可以遍历数组和每个子数组,直到匹配您的项目为止。
<?php
$array =
[
"int" => [80,85,66],
"text" => [57,58],
"varchar" => [82,72,70],
"decimal" => [60,61]
];
function find_type($needle, $array)
{
foreach($array as $type => $sub)
foreach($sub as $int)
if($int == $needle) return $type;
}
echo find_type(60, $array);
输出:
decimal