动态更新一个函数的PHP数组
我有多个站点地图,我想合并它们,但在合并它们之前,我需要为所有数组中的所有值附加一个唯一变量。动态更新一个函数的PHP数组
// The global variable
define("BASE_URL", "http://domain.com");
$sitemap_full = [ "home" => BASE_URL ];
// One of the arrays
$sitemap_example = [
"foo" => "/bar",
"gnu" => "/lar"
];
由于我有多个这些数组,我想创建一个函数来追加链接。
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
return $sitemap[$title] = BASE_URL . $url;
}
}
,并在行动将是:
pushToSitemap($sitemap_example, $sitemap_full);
但是,这是行不通的,因为如果我print_r($sitemap_full);
它会显示Array("home", "http://domain.com");
。
真正让我感到困扰的是,如果在函数中我回应它们,它们将被回显。
我在做什么错?
编辑
应该显示
Array(
"home" => "http://domain.com"m
"foo" => "http://domain.com/bar",
"gnu" => "http://domain.com/lar
);
你的问题似乎谎言你foreach
函数中:
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
return $sitemap[$title] = BASE_URL . $url;
}
}
您返回只是一个单一的项目,更重要的是,格式化关闭。
相反,
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
$sitemap[$title] = BASE_URL . $url;
}
return $sitemap;
}
$sitemap_full = pushToSitemap($sitemap_example, $sitemap_full);
我猜他甚至不想返回任何内容,只是执行该操作以便Sitemaps“刷新” 。 –
@DawidZbiński - 你怎么看? – Derek
好的,我的坏。现在我意识到他想合并它们。 –
你foreach'的'非常第一次迭代中返回在'pushToSitemap()'函数,所以它永远不会继续迭代;只有在'foreach'循环终止后才会返回 –
那么^^^^然后也许你应该向我们展示你想要数组看起来像什么,因为它对我来说不完全明显 – RiggsFolly
'var_dump(array_merge( $ sitemap_full,array_map(function($ value){return BASE_URL。$ value;},$ sitemap_example)));' –