Php json数组正在重复索引
这是我的代码:Php json数组正在重复索引,php,json,Php,Json,这是我的代码: 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', f
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地址:“0.0.0.0/0”,“pref src:”“网关:“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"}].
有人能帮我吗?您需要在每次循环中初始化阵列,否则每次都只是添加到阵列中,因此会出现重复 您还需要将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);
您的第一个输出有语法错误,这是出于设计吗?另外,为什么不直接进行
json\u编码(array\u unique($array))
?这将消除所有重复项。它显示错误“数组到字符串转换”@GrumpyCroutonThank@RiggsFolly当我移动回显并初始化数组以避开循环时,它会工作。