2014-06-13 89 views
0

所以,我有以下代碼:count次X出現在JSON

{ 
    "request": { 
     "data_start": "2013-01-01", 
     "data_end": "2014-06-13" 
    }, 
    "response": { 
     "status": 1, 
     "httpStatus": 200, 
     "data": { 
      "data": [{ 
       "Stat": { 
        "offer_id": "8", 
        "clicks": "0", 
        "date": "2013-01-14", 
        "month": "01", 
        "year": "2013", 
        "affiliate_id": "1000" 
       } 
      }, { 
       "Stat": { 
        "offer_id": "8", 
        "clicks": "26", 
        "date": "2013-02-06", 
        "month": "02", 
        "year": "2013", 
        "affiliate_id": "1000" 
       } 
      }, { 
       "Stat": { 
        "offer_id": "8", 
        "clicks": "12", 
        "date": "2013-02-06", 
        "month": "02", 
        "year": "2013", 
        "affiliate_id": "2" 
       } 
      } 
      }] 
     } 
    } 
} 

我需要知道有多少次「約會」:「2013年2月6日」,例如出現在此JSON,使用PHP。這可能嗎?只是要清楚,這只是一個例子,實際的JSON數千行。

謝謝!

+0

你有它作爲一個PHP對象或字符串? – Prashant

+0

另外,你的JSON對象似乎很糟糕。檢查jslint.com首先更正您的JSON並編輯問題以重新發布有效的JSON – Prashant

+0

您對字符串嘗試了'json_decode()',然後遍歷數據數組? –

回答

0

下面Mike指出的最快方法是使用substr_count()。這在C中以PHP中的本地方法實現。此方法不會考慮重疊模式(請參閱PHP文檔中的示例)。

如果針每次完全相同並且包含重疊,則可以循環並使用strpos,每次移動偏移量。

$offset = 0; 
$count = 0; 
while(($offset = strpos($json, '"date": "2013-02-06"', $offset) !== false) { 
    $offset++; 
    $count++; 
} 

如果針頭未在每種情況下精確另一種選擇(多餘的空格等):

$count = preg_match_all('"[dD]ate":\w+"2013-02-06"', $json); 

正則表達式是需要慢所以只能使用。

如果數據需要更密集地使用,最好的方法是反序列化並從那裏開始。反序列化將導致> 2倍的內存利用率,並導致反序列化所需的週期。考慮每種方法的權衡是很重要的。

+1

如果有人正在使用字符串操作方法,爲什麼不只是'$ count = substr_count($ json,$ date_search_string)'? –

+0

因爲我真的忘了它在那裏。絕對是這種情況下更好的解決方案,但substr_count不會考慮重疊實例。上面的方法會(將這添加爲未來讀者的警告)。 –

0

作爲@PrashantBalan提出,如果它是一個字符串,你可以做一個真正簡單的計數。一種方法是將字符串拆分爲數組,使用「date」:「2013-02-06」作爲分隔符,然後返回數組中元素的數量(減一)。

+0

感謝您的認可。 :) – Prashant

+0

@PrashantBalan我敢打賭,你的答案會比我的僞代碼更優雅,更具描述性! – BrettFromLA

+0

我剛剛4年學習PHP。 :) – Prashant

0

只需簡單地反序列化JSON,並在搜索日期內過濾其中的數據數組。

$json = '...'; // your JSON string 
$obj = json_decode($json); 
$data_array = $obj->response->data->data; 
$search_date = '2013-02-06'; // whatever your search date is 

// filter the data array down to those items matching the date 
$filtered_data = array_filter($data_array, function($item) use ($search_date) { 
    return $item->Stat->date = $search_date; 
} 
// get count of filtered items 
$filtered_count = count($filtered_data);