[英]get key with specific value from multidimention array
i have an array like below: 我有一个像下面这样的数组:
$array=["satu"=>"mangga","dua"=>array("melon","apel")];
how can i get "dua" with $buah="melon" 我如何用$ buah =“ melon”获得“ dua”
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". 我尝试使用这种方法,当$ buah =“ mangga”时,输出为“ satu”,但是当$ buah =“ melon”时我什么也没得到,我怎么能通过$ buah =“ melon”得到“ dua”。 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;
}
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. 如果想使它对于任何结构都是全局的,可以将foreach放在一个函数中,并可以对其进行递归调用。 Hope this help :) 希望这个帮助:)
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);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.