0

I have this:

Array
(
    [carx] => Array
        (
            [no] => 63

        )

    [cary] => Array
           (
           [no] => 64

           )
)

How can I find the key carx when i have the no=63 ? i know how to use array_search() but this one is a bit tricky. Like i can find key name id while I have 63 But this one is a bit tricky.

can someone help me ?

  • possible duplicate of [fastest way to get parent array key in multidimensional arrays with php](http://stackoverflow.com/questions/2776107/fastest-way-to-get-parent-array-key-in-multidimensional-arrays-with-php) – Gordon Dec 08 '10 at 15:15

3 Answers3

1
foreach ($array as $i => $v) $array[$i] = $v['no'];
$key = array_search(63, $array);
rik
  • 8,592
  • 1
  • 26
  • 21
0

So you don't you your id key for the first level, so loop through and when you find a match stop looping and break out of the foreach

$id = 0;
$needle = 63;
foreach($array as $i => $v)
{
    if ($v['no'] == $needle)
    {
        $id = $i;
        break 1;
    }
}
// do what like with any other nested parts now
print_r($array[$id]);

Then you could use that key to get the whole nested array.

tristanbailey
  • 4,427
  • 1
  • 26
  • 30
0

Is this of any use? I use it to do generic searches on arrays and objects. Note: It's not speed/stress tested. Feel free to point out any obvious problems.

function arrayKeySearch(array $haystack, string $search_key, &$output_value, int $occurence = 1){
    $result             = false;
    $search_occurences  = 0;
    $output_value       = null;
    if($occurence < 1){ $occurence = 1; }
    foreach($haystack as $key => $value){
        if($key == $search_key){
            $search_occurences++;
            if($search_occurences == $occurence){
                $result         = true;
                $output_value = $value;
                break;
            }
        }else if(is_array($value) || is_object($value)){
            if(is_object($value)){
                $value = (array)$value;
            }
            $result = arrayKeySearch($value, $search_key, $output_value, $occurence);
            if($result){
                break;
            }
        }
    }
    return $result;
}