[英]Search mutlidimensional array for a value and return key in PHP
我有一個看起來像這樣的數組:
$user = array();
$user['albert']['email'] = 'an@example.com';
$user['albert']['someId'] = 'foo1';
$user['berta']['email'] = 'another@example.com';
$user['berta']['someId'] = 'bar2';
現在我想找出哪個用戶有某個someId
。 在這個例子中,我想知道誰有someId
bar2
並想要結果berta
。 有沒有一個像樣的PHP功能,或者我必須自己創建它?
$id = 'bar2';
$result = array_filter(
$user,
function($u) use($id) { return $u['someId'] === $id; }
);
var_dump($result);
注意:這適用於PHP 5.3+。
注2:現在沒有理由使用下面的任何版本。
嘗試此函數它將返回匹配數組。
function search_user($id) {
$result = new array();
foreach($user as $name => $user) {
if ($user['someId'] == 'SOME_ID') {
$result[] = $user;
}
}
return $result;
}
如果你總是有一個具有相同id的用戶,那么你可以只返回一個用戶,否則拋出異常
function search_user($id) {
$result = new array();
foreach($user as $name => $user) {
if ($user['someId'] == 'SOME_ID') {
$result[] = $user;
}
}
switch (count($result)) {
case 0: return null;
case 1: return $result[0];
default: throw new Exception("More then one user with the same id");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.