1

I cannot for the life of me figure out how to search through a multidimensional array for a key => value pair, and then either A) Return the array it belongs to or a different specific key => value pair that exists in the same array.

My array is:

$pages = array(
    array(
        'pageId' => 10,
        'title' => 'Welcome',
        'theme' => 'basic'
    ),
    array(
        'pageId' => 11,
        'title' => 'Home',
        'theme' => 'basic'
    ),
    array(
        'pageId' => 12,
        'title' => 'Login',
        'theme' => 'basic'
    )
);

I've tried

$theme = array_search(10, array_column($search, 'pageId'));

but it keeps returning an int and not the value basic as I am wanting.

I would like either just the value or an array with the key => value pair or the whole array it belongs to.

1
  • are you talking about this 'theme' => 'basic'? Do you want basic which is the value of theme? Commented Jun 23, 2017 at 4:10

2 Answers 2

3

Try this simplest one, hope this will be helpful. Here we are using array_column

Try this code snippet here

$result=array_column($pages,"theme" ,'pageId');
if(isset($result[$toSearch]))
{
    echo $result[$toSearch];
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is EXACTLY what I was looking for. Thanks!
0

You can use array_filter, live demo.

array_filter($array, function($v) use($searchKey, $searchValue) {
  return $v[$searchKey]  == $searchValue;
});

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.