0

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

2
  • Just an example -- but 4bf58dd8d48988d155941735 relates to a pub parent Commented Sep 6, 2016 at 9:36
  • they are different id's man Commented Sep 6, 2016 at 9:36

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers man - this solved it - yes - the solution was more simple - just getting flustered.
2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.