[英]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.