我有一些数组,下面是这些数组的两个例子。我想得到键模式的值。我们不知道这些数组在哪个索引处。我尝试了以下几点:
$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()将只搜索第一个维度中的键。多维数组中的嵌套键将找不到。
发布于 2017-02-05 01:58:24
这将递归地调用自己,直到找到第一个键,并返回值。它可能会被扩展为收集所有值,甚至可以向每个值返回一个索引数组。
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']https://stackoverflow.com/questions/42047589
复制相似问题