[英]How to get the value of a specific key in multi-dimensional array PHP
我有一些数组,下面是这些数组的2个示例。 我想了解按键模式的价值。 我们不知道这些数组在哪个索引处。 我尝试了以下方法:
$text1 = array(
'type'=>'balance',
'lang'=> array(
'text'=>array(
'en'=>array('mode'=>'ussd', 'tet'=>'Your balance is'),
'ru'=>array('mode'=>'ussd', 'tet'=>'vash balance'),
),
),
);
$text2 = array(
'type'=>'balance',
'lang'=> array(
'text'=>array(
'en'=>array(
'success'=>array(
'mode'=>'ussd',
'tet'=>'Your balance is'),
'error'=>array(
'mode'=>'ussd',
'tet'=>'Your balance is err')
),
'ru'=>array(
'success'=>array(
'mode'=>'ussd',
'tet'=>'vash balans'),
'error'=>array(
'mode'=>'ussd',
'tet'=>'vash balans is err'
)
),
),
),
);
function GetKey($key, $search)
{
foreach ($search as $array)
{
if (array_key_exists($key, $array))
{
return $array[$key];
}
}
return false;
}
$tmp = GetKey('mode' , $text1);
echo $tmp;
返回值:警告:array_key_exists()期望参数2为数组,第27行的C:\\ xampp \\ htdocs \\ test \\ index.php中给出的字符串
根据php.net:array_key_exists()将仅在第一维中搜索键。 找不到多维数组中的嵌套键 。
这将递归调用自身,直到找到第一个键,然后返回值。 它可能会被扩展以收集所有值,甚至将索引数组返回给每个索引。
function GetKey($key, $array) {
if (is_array($array)) {
foreach ($array as $k => $v) {
if ($k == $key) {
return $v;
} elseif (is_array($v)) {
return GetKey($key, $v);
}
}
} else {
return false;
}
}
编辑 :查找所有值。 该函数现在不返回,只是通过使用global
,将结果一直推入所有递归都在其范围内的数组。
function GetKey($key, $array) {
global $results;
if (is_array($array)) {
foreach ($array as $k => $v) {
if ($k == $key) {
$results[] = $v;
} elseif (is_array($v)) {
GetKey($key, $v);
}
}
}
}
$results = array();
GetKey('mode', $text1);
// $results is now: ['ussd', 'ussd']
$results = array();
GetKey('mode', $text2);
// $results is now: ['ussd', 'ussd', 'ussd', 'ussd']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.