【问题标题】:PHP get array items based on string maskPHP根据字符串掩码获取数组项
【发布时间】:2016-09-27 22:05:31
【问题描述】:

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

{
   "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 进行破解,但我不希望它会成功

【问题讨论】:

  • 那不是json字符串吗?除非它已经解码,并且您没有向我们展示完整的代码,并且不应该那些列应该是 [] 大括号
  • 我只是将数组转换为 json 用于显示目的。我找到了解决方案。稍后发布
  • 哦,好吧,当然,自我回答在 SO 中很好

标签: php arrays multidimensional-array


【解决方案1】:

所以在被困在这个问题上几个小时之后.. 并将其发布在这里。我找到了解决办法

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

【讨论】:

    猜你喜欢
    • 2018-08-16
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多