2017-07-06 43 views
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"}]. 

誰能幫助我?

+0

你的第一個輸出有一個語法錯誤,這是由設計? – GrumpyCrouton

+0

另外,爲什麼不只是'json_encode(array_unique($ array))'?這將擺脫所有重複。 – GrumpyCrouton

+0

它顯示錯誤「數組到字符串轉換」@GrumpyCrouton –

回答

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); 
+0

感謝@RiggsFolly當我移動回聲和初始化數組到外部循環時,它工作。 –