Solved

php merging arrays with the same location or key

Posted on 2011-03-15
3
291 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 500 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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…

758 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now