PHP根据字符串掩码获取数组项


PHP get array items based on string mask

我有一个包含一堆记录的数组,如:

{
   "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"
   }
}

我如何做到这一点?我现在完全卡住了:(忙着尝试一个hack的array_combine现在,但我不抱太大的希望它会工作

所以在被困在这几个小时之后…然后贴在这里。我找到了一个解决方案

$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;
}