2

I've got an array with nested arrays, and I was trying to use the *search_array* function to sift through the array and give me back their keys. It hasn't been working. Here's the code:

<?php 
$array = array(
 'cat1' => array(1,2,3),
 'cat2' => array(4,5,6),
 'cat3' => array(7,8,9),
);
foreach($array as $cat){
 if(is_array($cat)
 echo array_search(5,$cat); //want it to return 'cat2'
 else
 echo array_search(5,$array);
}

Thanks!

asked Nov 27, 2010 at 8:16

2 Answers 2

3

If you always have a two-dimensional array, then it is as easy as:

function find($needle, $haystack) {
 foreach($haystack as $key=>$value){
 if(is_array($value) && array_search($needle, $value) !== false) {
 return $key;
 }
 }
 return false;
}
$cat = find(5, $array);
answered Nov 27, 2010 at 10:19
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That's precisely what I was looking for.
2
function mySearch($haystack, $needle, $index = null)
{
 $aIt = new RecursiveArrayIterator($haystack);
 $it = new RecursiveIteratorIterator($aIt); 
 while($it->valid())
 { 
 if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
 return $aIt->key();
 } 
 $it->next();
 } 
 return false;
}
$array = array(
 'cat1' => array(1,2,3),
 'cat2' => array(4,5,6),
 'cat3' => array(7,8,9),
);
echo $arr_key = mySearch($array, 5); 

this will give u the answer

Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
answered Nov 27, 2010 at 8:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.