0

i have an array like below:

$array=["satu"=>"mangga","dua"=>array("melon","apel")];

how can i get "dua" with $buah="melon"

I tried with this method, when $buah = "mangga" , the output is "satu" but when $buah = "melon" i got nothing, how can i get "dua" with $buah="melon". thank you

$array=["satu"=>"mangga","dua"=>array("melon","apel")];
   $buah = "melon";
   $a = array_search($buah,$array);
        if(is_array($a)){
          $x= array_search($buah,$a);
          echo $x;
        }else{
          echo $a;
        }
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Sandhi
  • 89
  • 2
  • 11

2 Answers2

1

try this code, it will work for your array structure,

<?php
$array=array(
    "satu"=>"mangga",
    "dua"=>array(
            "melon",
            "apel",
            ),
    );
    foreach($array as $key=>$value)
    {
        if(is_array($value))
        {
            foreach($value as $key1=>$value1)
            {
                if($value1=="melon")
                {
                    echo $value1;
                }   
            }
        }
        else if($value=="melon")
        {
            echo $value;
        }
    }
?>

How ever if you want to make it global for any structure you can put foreach inside one function and can make recursive call of that. Hope this help :)

GTS Soft.
  • 187
  • 4
0

See this may help:

<?php 
$haystack=array("satu"=>"mangga","dua"=>array("melon","apel"));
   $needle = "melon";


        function recursive_array_search($needle,$haystack) {
            foreach($haystack as $key=>$value) {
                $current_key=$key;
                if(is_array($value)) {
                   foreach($value as $val){
                                if($needle == $val)
                                    echo $current_key;
                            }

            }else if($needle == $value){
                echo $current_key;
            }
        }
        }
        recursive_array_search($needle,$haystack);

        ?>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44