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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.