2017-05-30 62 views
0

我的JSON字符串:如何計算具體子在JSON

{ 
    "nearby_drivers": [ 
    { 
     "drivers": [ 
     { 
      "locations": [ 
      { 
       "lat": 38.670808, 
       "lng": -121.49624 
      }, 
      ] 
     }, 
     { 
      "locations": [ 
      { 
       "lat": 38.625728, 
       "lng": -121.514559 
      }, 
      ] 
     } 
     ], 
     "ride_type": "lyft" 
    } 
    ] 
} 

我想要做的就是一個總數爲(緯度,經度)在PHP對。我已經在計算1 lat或1 lng方面取得了成功。但我不知道如何做到這一點。可以做到嗎?感謝您的時間。

+0

先將其轉換爲與json_decode一個對象,然後array_filter或array_reduce會做訣竅。 – mkaatman

+0

請提供您的預期輸出爲您張貼的樣本輸入。如果有任何邊緣案例需要考慮,請添加這些樣本輸入和您的預期輸出。 – mickmackusa

回答

0

我說保持簡單,只是做一個字符串計數沒有任何類型的轉換:

$input='{ 
    "nearby_drivers": [ 
    { 
     "drivers": [ 
     { 
      "locations": [ 
      { 
       "lat": 38.670808, 
       "lng": -121.49624 
      }, 
      ] 
     }, 
     { 
      "locations": [ 
      { 
       "lat": 38.625728, 
       "lng": -121.514559 
      }, 
      ] 
     } 
     ], 
     "ride_type": "lyft" 
    } 
    ] 
}'; 

echo "lat count = ",substr_count($input,'"lat"'),"<br>"; 
echo "lng count = ",substr_count($input,'"lng"'); 

輸出:

lat count = 2 
lng count = 2 
+0

然後,如果您需要從字面上計算對(如其中一個可能獨立),那麼可以使用正則表達式來實現。 – mickmackusa

+0

很好地完成了,謝謝。 –