Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

php merging arrays with the same location or key

Posted on 2011-03-15
3
Medium Priority
?
359 Views
Last Modified: 2012-05-11
I have to following two arrays that I would like to combine using php. How do I do this?

Array1
(
    [0] => Location 1
    [1] => Streamflow
)
, Array2
(
    [0] => Location 1
    [1] => Gage
)


Combine the arrays into a single array like this:
Array
(
    [0] => Location 1
    [1] => Streamflow
    [2] => Gage
)


Thanks!
0
Comment
Question by:kent3800
3 Comments
 
LVL 9

Expert Comment

by:Vampireofdarkness
ID: 35144910
As long as you're omitting 'Location 1' as the text is the same:

	$a1=array(0=>'Location 1',1=>'Streamflow');
	$a2=array(0=>'Location 1',1=>'Gage');

	foreach($a2 as $key => $value) {
		if(!in_array($value, $a1)) {
			$a1[]=$value;
		}
	}

	print_r($a1);

Open in new window

0
 
LVL 3

Accepted Solution

by:
Manikandan1986 earned 2000 total points
ID: 35145189
Try this

<?php

$a1=array(0=>'Location 1',1=>'Streamflow');
$a2=array(0=>'Location 1',1=>'Gage');

$a3 = array_merge($a1, $a2);
echo "Merged Array : <br>";
print_r($a3);
echo "<br>Merged Unique Array : <br>";
$a4 = array_unique($a3);
print_r($a4);

?>

Output:

Merged Array :

Array
(
    [0] => Location 1
    [1] => Streamflow
    [2] => Location 1
    [3] => Gage
)

Merged Unique Array :


Array
(
    [0] => Location 1
    [1] => Streamflow
    [2] => Gage
)
0
 
LVL 4

Author Closing Comment

by:kent3800
ID: 35409829
Awesome. Thanks.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
The first step to building an amazing About page is to figure out what you want the page to say about your company. You then must grab the attention of the reader, boast a bit, tell a story and let others brag about you. With a little bit of thought…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
This video teaches users how to migrate an existing Wordpress website to a new domain.
Suggested Courses

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question