在php中组合/合并数组

时间:2016-08-05 18:32:03

标签: php arrays merge array-merge

我正在尝试将一组数据传递给我的html页面模板,以填充页面上缺少的数据。这是我拥有的数组和正在发生的问题。

protected $data = [
    "head" => [
            "css" => ["main"], /*add other default css files here*/
            "meta" => ["description" => HTML_DESCRIPTION, "keywords" => HTML_KEYWORDS, "charset" => HTML_CHARSET], // add other meta data here
            "JS" => [/*"src"*/], //set default js scripts here
            "title" => [0 => HTML_TITLE]
        ],
    "body" => [
        "title" => [
            "text" => BODY_TITLE_TEXT
        ],
        "navigation" => [
            "links" => [
                "Home" => "home",
                "Blog" => "blog"
            ]
        ]
    ]
];

以下是我试图让它发挥作用的代码。

    // $title = ["text" => "NEW TITLE"]

    public function build($title = [], $navigation = []){
    $defualts = $this->data;
    $data_to_add["body"] = ["title" => $title, "navigation" => $navigation];
    $data = array_merge_recursive($defualts,$data_to_add);
    require_once APP."/view/templates/body.php";
}

我从中得到的结果

array(2) {
  ["head"]=>
  array(4) {
    ["css"]=>
    array(1) {
      [0]=>
      string(4) "main"
    }
    ["meta"]=>
    array(3) {
      ["description"]=>
      string(15) "DESCRIPTION"
      ["keywords"]=>
      string(41) "KEY1,KEY2,KEY3"
      ["charset"]=>
      string(5) "UTF-8"
    }
    ["JS"]=>
    array(0) {
    }
    ["title"]=>
    array(1) {
      [0]=>
      string(15) "SITE TITLE"
    }
  }
  ["body"]=>
  array(2) {
    ["title"]=>
    array(1) {
      ["text"]=>
      array(2) {
        [0]=>
        string(15) "OLD TITLE"
        [1]=>
        string(9) "NEW TITLE"
      }
    }
    ["navigation"]=>
    array(1) {
      ["links"]=>
      array(2) {
        ["Home"]=>
        string(4) "home"
        ["Blog"]=>
        string(4) "blog"
      }
    }
  }
}

正如您所看到的,不是将$ data [body] [title] [text]替换为NEW TITLE,而是将文本从字符串更改为包含两个值的数组。我知道array_merge_recursive就是这个原因。我只是在尝试编写代码以在值已经是数组时创建数组并且如果不是则替换值时遇到麻烦。

例如,如果我有一个带有特殊导航的模板页面,我可能想要添加$ data [“navigation] [”links“] [”sublinks“] [”sublink1“,”sublink2“,”sublink3“]使用array_merge_recursive()我无法添加子链接数组并同时将“OLD TITLE”替换为“NEW TITLE”。

感谢社区提供的任何帮助!

1 个答案:

答案 0 :(得分:0)

我会保持简单并直接设置值,而不是使用array_merge_recursive

$data = $this->data;
$data['body']['title'] = $title;
$data['body']['navigation'] = $navigation;