Manipulate last iteration of foreach inside foreach

I’ve created an array from three variables I get through a foreach loop.

//loop through each post
foreach($loop as $p){
    //get the meta and taxonomy data
     $term_list = get_the_term_list($p, "mountains",true);
     $name = trim($term_list, "1");
     $wtr_long = get_post_meta($p,"wtr_longitude",true);
     $wtr_lat = get_post_meta($p,"wtr_latitude",true);

    //Add to Array
    $map_array[] = array ($name => $wtr_lat . "|" . $wtr_long);

}

Now this array should then deliver the data that will populate my Google Map, for that I’m using below code.

Read More
                foreach( $map_array as $a){
                       foreach ($a as $key => $value) { 
                                    $pieces = explode("|", $value);
                                    $trimmed_key = trim($key, "1");
                                    $name = trim($trimmed_key);
                       ?>

                                    {latitude: <?php echo $pieces[0]; ?>,
                                    longitude: <?php echo $pieces[1]; ?>,
                                    html: <?php echo $name; ?>},
                    <?php }} ?>

This works almost fine (although it’s probably not the cleanest code, tips on this would be appreciated too). The issue I’m having is that in the last iteration of the foreach inside the other foreach, I need to add a ], resulting in:

html: <?php echo $name; ?>}],

I can escape a single foreach, but doing it on a foreach inside a foreach is driving me insane. Any help would be greatly appreciated.

Related posts

Leave a Reply

2 comments

  1. I’m not a php develeopor but you may want to build the collection of strings you want to echo first. After the collection is complete you can add the ‘]’ the the last element. Then echo each element in your collection of strings.

  2. atbyrd, your approach gave me a couple new issues, but did in the end lead to a working solution. Thank you for that.

    Below the code that fixed the issue, hope it’ll be helpful to someone else in the future.

    //Add to Array
    $map_string .= '{latitude: "' . $wtr_lat . '", longitude: "' . $wtr_long . '", html: "' . $name .'"},~!~';
    //$map_string .= '{latitude: "' . $wtr_lat . '", longitude: "' . $wtr_long . '", html: "name"},~!~';
    }
    
    //Remove last three "~!~" characters from the string not to have one too many arrays when exploding
    $clean_map_string = substr($map_string, 0, -3);
    
    //Now I can explore on ~!~ to get a new array with the correct strings
    $map_array = explode('~!~', $clean_map_string);
    $i = 0;
    $length = count($map_array)-1;
    
    //Inserts all the markers
    foreach($map_array as $value){
    if( $i != $length ){
    echo $value;
    }
    else {
    echo str_replace("},", "}],", $value);
    }
    $i++;