通过匹配子对象的键值获取JSON键 [英] Get JSON key By Matching sub-object's key value
本文介绍了通过匹配子对象的键值获取JSON键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个json字符串:
I have a json string:
$testArray =
{
"Test1": {
"id": "26",
"admin": "Admin TestClient"
},
"Test2": {
"id": "27",
"admin": "Admin TestClient"
},
"Test3": {
"id": "28",
"admin": "Admin TestClient"
}
}
还有一个具有id值的变量,例如
And a variable with id value, say
$idSearch = 28;
现在我需要获取其密钥:"Test3"
Now I need to get its key : "Test3"
我尝试过:
$NameKey = array_search($idSearch , $testArray->id);
但这给出了空值
推荐答案
为此,最好使用一个简单的循环:
For this, it's better to use a simple loop:
function getById($id) {
foreach ($testArray as $key => $value) {
if ($value['id'] == $id) {
return $key;
}
}
return '';
}
$key = getById(28);
var_dump($key);
这篇关于通过匹配子对象的键值获取JSON键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文