我正在尝试在函数中归纳一些代码,以便可以读取不同的JSON格式的输入并从每个输入确定系统信息。为简便起见,我不包括所有代码。在实际的代码中,我正在从数据库中检索$ length的值。
这里是一个例子:
function readHostname($json, $length) {
$content = json_decode($json, true);
$hostname = $content[$length];
}
$json = file_get_contents($url1, false, $context);
$length = "[0]['cluster']['nodes'][0][hostName]";
echo readHostname($json, $length);
$json = file_get_contents($url2, false, $context);
$length = "[0]['components']['serviceName']";
echo readHostname($json, $length);
作为参考,URL1将返回JSON,例如:
[
{
"cluster": {
"nodes": [
{ "name": "cluster1",
"hostName": "alpha"
},
{ "name": "cluster2",
"hostName": "beta"
}
]
}
},
{
"cluster": {
"nodes": [
{ "name": "prod_cluster1",
"hostName": "oscar"
},
{
"name": "prod_cluster2",
"hostName": "delta"
}
]
}
}
]
和url2将返回json:
[
{
"compenents": {
"serviceName" : "hostname1",
"environment" : "produciton"
}
}
]
答案 0 :(得分:0)
您想要灵活地访问嵌套数组结构。将此替换为readHostname
函数:
function readHostname($json, $length) {
$content = json_decode($json, true);
preg_replace_callback('/\[([^]]+)\]+/', function($m) use(&$content) {
$index = $m[1];
$content = $content[preg_match('/[0-9]+/', $index) ? intval($index) : trim($index, "'\"")];
}, $length);
return $content;
}
答案 1 :(得分:0)
您可以抽象该过程并使用递归。
function getHost($payload,$hostName){
$array = is_array($payload) ? $payload : json_decode($payload,true);
if(json_last_error() != JSON_ERROR_NONE){
return;
}
foreach(array_keys($array) as $key){
if($array[$key] == $hostName){
unset($array[$key]);
return $array[key($array)];
}
}
return getHost($array[key($array)],$hostName);
}
echo getHost($payload,"cluster1");
echo getHost($payload,"hostname1");