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". thank you
我试过这种方法,当$ buah =“mangga”时,输出是“satu”但是当$ buah =“melon”我什么都没有时,我怎么能用$ buah =“melon”获得“dua”。谢谢
$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;
}
2 个解决方案
#1
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 :)
但是如果你想让它为任何结构都是全局的,你可以将foreach放在一个函数中,并且可以对它进行递归调用。希望这有帮助:)
#2
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);
?>
#1
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 :)
但是如果你想让它为任何结构都是全局的,你可以将foreach放在一个函数中,并且可以对它进行递归调用。希望这有帮助:)
#2
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);
?>