这是我的代码:
if ($API->connect("192.168.81.130", "admin", "")) {
$API->write('/ip/route/print', false);
$API->write('=.proplist=.id', false);
$API->write('=.proplist=dst-address', false);
$API->write('=.proplist=pref-src', false);
$API->write('=.proplist=gateway');
$result = $API->read();
$API->disconnect();
foreach ($result as $route){
$response['id'] = $route['.id'];
$response['dst-address'] = $route['dst-address'];
if (isset($route['pref-src'])) {
$response['pref-src'] = $route['pref-src'];
} else {
$response['pref-src'] = "";
}
$response['gateway'] = $route['gateway'];
$array[] = $response;
echo json_encode($array);
}
}
,输出为:
[{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"}][{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}]
结果为“[{”id“:”* 2“,”dst-address“:”0.0.0.0/0“,”pref-src“:”“,”thegateway“:”192.168.1.1“} ]“显示两次。
我想要这样的输出:
> [{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}].
任何人都可以帮助我吗?。
答案 0 :(得分:0)
每次循环时都需要初始化数组,否则每次只是添加它,因此重复
您还需要将json字符串的回显移动到循环外部
foreach ($result as $route){
$response = array();
$response['id'] = $route['.id'];
$response['dst-address'] = $route['dst-address'];
if (isset($route['pref-src'])) {
$response['pref-src'] = $route['pref-src'];
} else {
$response['pref-src'] = "";
}
$response['gateway'] = $route['gateway'];
$array[] = $response;
}
echo json_encode($array);