2017-07-06 40 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当我移动回声和初始化数组到外部循环时,它工作。 –