0

I have multiple sitemaps and I would like to merge them all, but before merging them, I need to append a unique variable to all values in all arrays.

// The global variable
define("BASE_URL", "http://domain.com");
$sitemap_full = [ "home" => BASE_URL ];

// One of the arrays
$sitemap_example = [
  "foo" => "/bar",
  "gnu" => "/lar"
];

Since I have multiple of those arrays, I wanted to create a function that will append the link.

function pushToSitemap($initial_sitemap, $sitemap) {
    foreach ($initial_sitemap as $title => $url) {
      return $sitemap[$title] = BASE_URL . $url;
    }
}

And in action in will be:

pushToSitemap($sitemap_example, $sitemap_full);

But this just doesn't work because if I print_r($sitemap_full); it will display Array( "home", "http://domain.com" );.

What really annoys me is that if in the function I echo them, they will be echoed.

What am I doing wrong?

EDIT

It should display

Array(
  "home" => "http://domain.com"m
  "foo" => "http://domain.com/bar",
  "gnu" => "http://domain.com/lar
);
3
  • 4
    you're returning inside the very first iteration of foreach in your pushToSitemap() function, so it never continues iterating; only return after the foreach loop terminates Commented Sep 27, 2016 at 23:22
  • That ^^^^ and then maybe you should show us what you want the array to look like after you have fiddled with it, as its not exactly obvious to me Commented Sep 27, 2016 at 23:23
  • var_dump(array_merge($sitemap_full, array_map(function($value) {return BASE_URL . $value; }, $sitemap_example))); Commented Sep 27, 2016 at 23:32

1 Answer 1

1

Your problem seems lie inside your foreach function:

function pushToSitemap($initial_sitemap, $sitemap) {
    foreach ($initial_sitemap as $title => $url) {
      return $sitemap[$title] = BASE_URL . $url;
    }
}

You are returning just a single item, what's more, the formatting is off.

Instead,

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I guess he doesn't even want to return anything and just do the action so the Sitemaps are "refreshed".
@DawidZbiński - how do you figure?
Ok, my bad. Now I realized that he wants to merge them.
@dcdeiv you have to reset the $sitemap_full variable to the contents of the function: $sitemap_full = pushToSitemap($sitemap_example, $sitemap_full);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.