2016-03-30 17 views
1

我正在研究一種從Wordpress數據庫提取內容並以不同方式處理內容的工具。我所做的一件事就是構建一個簡單的數組,名爲$category,其中包含wp_terms where term_id = <what the user picked>的內容。重建數組

不幸的是,它並不包含我想要的所有東西,所以我也填充了$category->taxonomy以及來自wp_term_taxonomy where term_id = <what the user picked>的相關細節。這是一對一的關係,所以沒有問題。

但是,我還得到了一堆我需要的東西wp_termsmeta,其中有多條線的一對多關係和相同的term_id。因此,我得到的是這樣的:

{ 
    "term_id" : 9813, 
    "name" : "Who's Who", 
    "slug" : "ww", 
    "term_group" : 0, 
    "taxonomy" : 
    { 
    "term_taxonomy_id" : 9832, 
    "term_id" : 9813, 
    "taxonomy" : "category", 
    "description" : "Who's Who is the CSICON Network's very own show about Doctor Who!", 
    "parent" : 0, 
    "count" : 58 
    }, 
    "meta" : [ 
    { 
     "meta_id" : 8490, 
     "terms_id" : 9813, 
     "meta_key" : "hosts", 
     "meta_value" : "1, 2" 
    }, 
    { 
     "meta_id" : 8492, 
     "terms_id" : 9813, 
     "meta_key" : "thumbnail", 
     "meta_value" : "http://csicon.fm/wp-content/uploads/2015/12/ww_4-248x248.jpg" 
    } 
    ] 
} 

我們在$categoryterm_idnameslug,並且term_groupwp_terms,然後在$category->taxonomy一堆東西,然後$category->meta下了一堆東西。

而現在問題

如果我想訪問縮略圖URL,我將不得不遍歷到$category->meta[1]->meta_value,但我不知道它會是[1]。對於其他類別,可能是[0][2]。我所知道的是,它是[n]meta_key = thumbnail

理想情況下,我希望通過meta一個很好的方式進行迭代,只是每個meta_key值保存爲$category下一個「真實」的關鍵,所以$category->thumbnail將返回meta_value當前存儲的......但我會解決以可靠的方式始終爲特定的meta_key找到正確的meta_value

有什麼想法? :)

解決

謝謝!而不是$category['meta'] = Category::find($term_id)->catMeta;,我現在運行下面的代碼,它正是我想要的。

$metaTemp = Category::find($term_id)->catMeta; 
$metaTable = json_decode(json_encode($metaTemp), FALSE); 
foreach($metaTable as $key => $value) { 
    $category[$value->meta_key] = $value->meta_value; 
} 

回答

1

我建議將元數據從數組轉換爲對象的屬性將是meta_keys。所以你得到這樣的結構:

{ 
    "term_id" : 9813, 
    "meta" : { 
    "hosts" : { 
     "meta_id" : 8490, 
     "terms_id" : 9813, 
     "meta_key" : "hosts", 
     "meta_value" : "1, 2" 
    }, 
    "thumbnail" : { 
     "meta_id" : 8492, 
     "terms_id" : 9813, 
     "meta_key" : "thumbnail", 
     "meta_value" : "http://csicon.fm/wp-content/uploads/2015/12/ww_4-248x248.jpg" 
    } 
    } 
} 

這樣,搜索正確的元將有一個不變的時間成本,而不是線性。

你的客戶會尋找它,像這樣:$category->meta->hosts

+0

如果有多個條目可以共享meta_key,那麼您將擁有數組而不是對象作爲元對象屬性。 – Weltschmerz

+0

這讓我朝着正確的方向前進,我發現了一個可行的解決方案!原文編輯。 –

0

謝謝!而不是$category['meta'] = Category::find($term_id)->catMeta;,我現在運行下面的代碼,它正是我想要的。

$metaTemp = Category::find($term_id)->catMeta; 
$metaTable = json_decode(json_encode($metaTemp), FALSE); 
foreach($metaTable as $key => $value) { 
    $category[$value->meta_key] = $value->meta_value; 
}