The Old County
The Old County

Reputation: 109

Returning specific parent key from a multidimensional array of values

I have a multidimensional array like this

$queryRequest = array(
   "Pub" => array(
      "4bf58dd8d48988d11b941735",
        "52e81612bcbc57f1066b7a06",
        "4bf58dd8d48988d155941735"
    ),
    "Gym" => array(
      "4bf58dd8d48988d175941735"
    )
);

I need to create a function that does a look up on an id -- and I need it to return the parent key.

So I have 4bf58dd8d48988d155941735 -- I need it to return Pub

$key = array_search($catId, $haystack); 

didn't work

Upvotes: 0

Views: 743

Answers (3)

Dave
Dave

Reputation: 111

You can try like this:

    $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 );
?> 

Upvotes: 2

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Simple foreachrequired,You can do it like below:-

<?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);

output:-https://eval.in/635957

Upvotes: 2

Noman
Noman

Reputation: 1487

Here you go:

<?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);
?>

DEMO

Upvotes: 1

Related Questions