Jump to content

How to get parent's array key?


marknt

Recommended Posts

Hi guys I need your help.

 

Guys I have this print_r array

Code:

 

<?

[2] => Array

        (

            [ 0 ] => Array

                (

                    [_parent_name] => User_model

                    [user_code] => jdelacruz

?>

 

The [2] there is the main array key and I used a function to search the jdelacruz value. So the function will return true but I need to find the array key which is [2] and store it in a variable. How can I do that?

 

Any suggestions?

 

Thanks in advance  ;)

Link to comment
https://forums.phpfreaks.com/topic/61500-how-to-get-parents-array-key/
Share on other sites

this is a test sample code. My real code is CI MVC with lots of models.

 

<?php
function rec_in_array($needle, $haystack, $alsokeys=false)
{
    if(!is_array($haystack)) return false;
    if(in_array($needle, $haystack) || ($alsokeys && in_array($needle, array_keys($haystack)) )) return true;
    else {
        foreach($haystack AS $element) {
            $ret = rec_in_array($needle, $element, $alsokeys);
        }
    }
   
    return $ret;
}

$array = array(
0 => 'blue', 
1 => 'red', 
2 => 'green', 
3 => 'red',
4 => array("sub1", "sub2")
);

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
$yo = array_search('sub1', $array);   

echo "<br><b>dito = $yo</b><br>";

$key = rec_in_array('sub2', $array);
print_r(array_keys($array));

echo "<pre>"; print_r($array); echo "</pre>";
echo "<br>" . $key . "<hr color=green>";
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.