我有像这样的多维数组
$queryRequest = array(
"Pub" => array(
"4bf58dd8d48988d11b941735",
"52e81612bcbc57f1066b7a06",
"4bf58dd8d48988d155941735"
),
"Gym" => array(
"4bf58dd8d48988d175941735"
)
);
我需要创建一个查找id的函数 - 我需要它来返回父键。
所以我有4bf58dd8d48988d155941735 - 我需要它来返回Pub
$key = array_search($catId, $haystack);
没有工作
答案 0 :(得分:2)
需要简单foreach
,您可以执行以下操作: -
<?php
$queryRequest = array(
"Pub" => array(
"4bf58dd8d48988d11b941735",
"52e81612bcbc57f1066b7a06",
"4bf58dd8d48988d155941735"
),
"Gym" => array(
"4bf58dd8d48988d175941735"
)
);
function searchparentkey($value,$arr){
foreach($arr as $key=>$val){
if(in_array($value,$val)) {
return $key;
}
}
}
echo $parent_key = searchparentkey("4bf58dd8d48988d11b941735",$queryRequest);
输出: - https://eval.in/635957
答案 1 :(得分:1)
你走了:
<?php
$queryRequest =
Array
(
(Pub) => Array
(
(0) => '4bf58dd8d48988d11b941735',
(1) => '52e81612bcbc57f1066b7a06',
(2) => '4bf58dd8d48988d155941735'
),
(Gym) => Array
(
(0) => '4bf58dd8d48988d175941735',
)
);
function searchName($id, $array) {
foreach ($array as $key => $val) {
if ($val['0'] === $id) {
return $key;
}
}
return null;
}
echo searchName('4bf58dd8d48988d11b941735', $queryRequest);
?>
答案 2 :(得分:1)
您可以尝试这样:
$queryRequest = array (
"Pub" => array (
"4bf58dd8d48988d11b941735",
"52e81612bcbc57f1066b7a06",
"4bf58dd8d48988d155941735"
),
"Gym" => array (
"4bf58dd8d48988d175941735"
)
);
function search_key($needle, $haystack)
{
return array_keys( array_filter( $haystack, function ($v) use($needle) {
return in_array( $needle, $v );
} ) );
}
$result = search_key( '52e81612bcbc57f1066b7a06', $queryRequest );
var_dump( $result );
?>