问题描述
我在https:// mysite / info中具有以下JSON响应:
{
"wg0": {
"privateKey": "[hidden]","publicKey": "XXXXXXXXXXXXXXXXXXX","listenPort": 0,"peers": {
"B3GtLuabWguXoG2Tz8KVukPXx3twn7A+X/SVT8=": {
"endpoint": "0.0.0.0:5377","latestHandshake": "Oct 28,2020 1:58:32 UTC","transferRx": "2.432 GB","transferTx": "1.098 GB","allowedIps": [
"10.85.85.2/32"
]
},"2Uqo3X2ubogU92LS4mWsZtF04ah3qJ4gt1g0=": {
"endpoint": "0.0.0.0:5412",2020 1:58:52 UTC","transferRx": "32.239 MB","transferTx": "220.852 MB","allowedIps": [
"10.85.85.3/32"
]
}
}
}
}
我需要在PHP中将“ allowedIps”值搜索到该响应中,并返回相应的“ latestHandshake”值。
例如:
$ch2 = curl_init();
curl_setopt($ch2,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch2,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch2,CURLOPT_URL,'https://mysite/info');
$result2 = curl_exec($ch2);
curl_close($ch2);
$obj2 = json_decode($result2);
$IPtoSearch = "10.85.85.2/32";
//Now How can I search $IPtoSearch into $obj2 and return latestHandshake value?
...
感谢帮助!
解决方法
很遗憾,您返回的JSON实际上无效,因为00000
不是有效的整数。如果您可以将00000
转换为0
,则JSON将成功解码,并且您可以找到与您的搜索IP地址相对应的latestHandshake
值,如下所示:
$obj2 = json_decode($result2,true);
$IPtoSearch = "10.85.85.2/32";
foreach ($obj2['wg0']['peers'] as $peer) {
if (in_array($IPtoSearch,$peer['allowedIps'])) {
$latestHandshake = $peer['latestHandshake'];
break;
}
}
echo "Last handshake for $IPtoSearch was at $latestHandshake\n";
输出(用于您的示例数据):
Last handshake for 10.85.85.2/32 was at Oct 28,2020 1:58:32 UTC