0
這是我的代碼: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', 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「:」「,」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"}].
誰能幫助我?
你的第一個輸出有一個語法錯誤,這是由設計? – GrumpyCrouton
另外,爲什麼不只是'json_encode(array_unique($ array))'?這將擺脫所有重複。 – GrumpyCrouton
它顯示錯誤「數組到字符串轉換」@GrumpyCrouton –