0

I have several array variables like this:

<?
$var_array["awal"]["kahiji"] = "Iyeu nu kahiji";
$var_array["awal"]["kadua"] = "Ayeuna kadua";
$var_array["akhir"]["sisanya"] = "Nu akhir pisan";
?>

I want to know the parent key of the key "kadua" which will produce "awal" in output, is it possible?, do I need to loop, or is there a simpler way to use functions from PHP ?, thanks in advance, your tricks or help will really help me.

1
  • It is Unclear by your (too simplistic) sample data whether you expect the first level key of the first qualifying item or if you expect to collect the first level keys of all qualifying items. Commented Nov 30, 2024 at 7:08

1 Answer 1

2

Sounds like you need to restructure your data.

You can't be sure that there won't be another parent for kadua that isn't awal so you will most likely have an array of keys unless you want to stop at the first or something like that.

I think this may be the sort of thing that object oriented programming could help you conceptualize.

Back to the question you actually asked, this is how I would try to solve it:

$first_keys = array();
foreach ($var_array as $key => $first_level){
    if (array_key_exists("kadua", $var_array[$key])){
        $first_keys[] = $key;
    }
}
//$first_keys has all first keys that had a second key of kadua
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I understand that I have to restructure the array of data, but right now I just want to know if there is an easy way to solve the above problem, by the way thank you for your suggestions and tricks :)

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.