2016-09-27 57 views
1

我有一大堆的記錄,如在數組數組項:PHP獲得基於字符串面具

{ 
    "ID": "38424", 
    "heading": "Nylies soek nuwe hoof", 
    "typeID": "1", 
    "datein": "2016-09-26 12:14:16", 
    "edited_datein": null, 
    "publishDate": "2016-09-23 00:00:00", 
    "category": { 
     "ID": "1", 
     "heading": "News", 
     "typeID": "3", 
     "datein": "2016-09-26 11:50:06", 
     "edited_datein": null, 
     "url": "news" 
    }, 
    "authorID": "592", 
    "tags": "skool,school,hoof,headmaster,etienne burger" 
} 

我有「列」我想

記錄將被「過濾」另一個數組
{ 
    "ID", 
    "heading", 
    "datein", 
    "category|heading", 
    "category|url" 
} 

我想結果來創建基於列項的多維數組:

{ 
    "ID": "38424", 
    "heading": "Nylies soek nuwe hoof", 
    "datein": "2016-09-26 12:14:16", 
    "category": { 
     "heading": "News", 
     "url": "news" 
    } 
} 

我如何實現這一目標?我現在完全卡在:(現在忙着嘗試array_combine的破解,但我沒有太多的希望,它會解決

+1

不是一個JSON字符串,除非它已經解碼的,你也不會向我們展示完整的代碼,並且不應該在兩列咋辦? [']'括號 – Ghost

+0

我只是將數組轉換爲json用於顯示目的,我找到了一個解決方案。很快發佈 – WilliamStam

+0

哦好吧,當然,自我回答在SO中很好 – Ghost

回答

0

所以在被困在這個很多小時後..並張貼在這裏。解決方案

$new_list = array(); 
foreach ($n as $record) { 
    $new_list[] = filter_columns($columns, $record); 
} 

和功能:

function filter_columns($columns, $record, $pre="") { 
    $return = array(); 
    foreach ($record as $key => $value) { // loop through the fields in the record 
     $str = $pre.$key; // create a string of the current key 
     if (in_array($str,$columns)){ 
      $return[$key] = $value; 
     } 
     if (is_array($value)){ 
      $return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask 
     } 


    } 

    return $return; 
}