Jump to content

Combining two arrays and keeping duplicates


sajjurocks

Recommended Posts

Okay, I have two associative arrays. (data comes from post)

 

Let's say:

 

$arr1 = array('1' => "a", '2' => "b", '1' => "c");
$arr2 = array('1' => "x", '2' => "y", '2' => "y");

 

My desired result after combining:

 

$arr3 = array('a' => "x", 'b' => "y", 'c' => "y");

 

Note that duplicates exist in both arrays. I just want to ignore those duplicates and generate result as mentioned above.

 

"array_combine" does exactly the same thing. But problem is that in case of duplicates, latter one prevails. I just want the same functionality as "array_combine" but it should keep duplicates as they are. (order also matters)

 

You can't have an array with duplicate keys. Don't know if the indexes are build with any logic in it, but I would let them auto generate. In that case, there's no risk of duplication and will be combined without truncation. For example:

 

<?php
$arr1 = array('a', 'b', 'c');
$arr2 = array('x', 'y', 'z');

$mix = array_combine($arr1, $arr2);
print_r($mix);
?>

So there is no way to keep duplicate keys in an array? Perhaps, it can be done by creating a custom small function or something like that? I'm a beginner so I don't exactly know how it can be done.

 

I'm actually getting data from user in a pair of input fields which gets stored in two different arrays. All I want is to combine both arrays such that values of first array should become "keys" of resultant array and values of second array should become "values" of resultant array.

 

Thanks for your reply though it didn't solve my problem.

Easy.

 

http://php.net/manual/en/function.array-combine.php

 

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

 

output

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

Thank you xyph. Did you read my first post?

 

I'm quoting some text from my first post.

 

"array_combine" does exactly the same thing. But problem is that in case of duplicates, latter one prevails. I just want the same functionality as "array_combine" but it should keep duplicates as they are. (order also matters)

You cannot have duplicate array keys. If you were to actually test the code you provided in the example and print_r() the resulting arrays, you'd see that. It would generate this:

 

Array
(
    [1] => c
    [2] => b
)
Array
(
    [1] => x
    [2] => y
)

Well, you CAN'T HAVE duplicate keys in an array. You could do this I guess :/

 

<?php

$arr1 = array('a','b','c','d');
$arr2 = array('x','y');

print_r( array_merge_fill($arr1,$arr2) );

print_r( array_merge_fill($arr2,$arr1) );

function array_merge_fill( $keys, $values ) {

   $return = array();
   $keyCount = count( $keys );   $valueCount = count( $values );
   if( $keyCount > $valueCount ) {
      for( $i = 0; $i < $valueCount; $i++ ) $return[$keys[$i]] = $values[$i];
      for( ; $i < $keyCount; $i++ ) $return[$keys[$i]] = end($values);
   } else {
      for( $i = 0; $i < $keyCount; $i++ ) $return[$keys[$i]] = $values[$i];
      for( ; $i < $valueCount; $i++ ) $return[end($keys).($i-$keyCount)] = $values[$i];
   }
   return $return;

}

?>

 

edit - I'll make a version that is able to use custom keys using foreach.

Another fix may be to store your arrays like this

 

<?php


$arr1 = array(
array(1,'a'),
array(2,'b'),
array(1,'c')
);


$arr2 = array(
array(1,'x'),
array(2,'y'),
array(2,'y')
);


print_r( merge_2d($arr1,$arr2) );


function merge_2d( $keys, $values ) {


$return = array();
foreach( $keys as $key => $arr )
	$return[] = array( $arr[1],$values[$key][1] );
return $return;


}


?>

Whatever you're trying to do, if you need duplicate keys, the logic is wrong. If you have 2 "a" indexes (a=>10, a=>20), how are you going to distinguish between different "a" key elements?

 

Show us the code of the inputs and how you get data from them, and I'm sure there is a way around.

Okay. I'm a newbie and learning, so don't expect a perfect code or even a good one. Anyway here it is (simplified version):

 

HTML:

<form name="input" action="" method="post">
Link# 1:  <input name="url[]" size="80" type="text" /><br />
Title# 1: <input name="title[]" size="80" type="text" /><br /><br />

Link# 2:  <input name="url[]" size="80" type="text" /><br />
Title# 2: <input name="title[]" size="80" type="text" /><br /><br />

Link# 3:  <input name="url[]" size="80" type="text" /><br />
Title# 3: <input name="title[]" size="80" type="text" /><br /><br />
.
.
.
.
.
.
.
.
.
.
(Users can add as many pairs of links and titles as they wish 
by clicking "Add" button which works with the help of javascript)

<input type="button" value="Add More" onClick="addInput('dynamicInput');" /> 
<input value="Generate!" name="submit" type="submit" />
</form>

 

PHP:

<?php

require('./functions.php');

$links = $_POST['url'];
$titles = $_POST['title'];

//$vlinks = array_combine($links, $titles);

$vlinks = array_combine(array_values($titles), array_values($links));

//print_r($vlinks);

foreach($vlinks as $title => $link)
	{
		if(strlen($link) >= 1 && strlen($title) >= 1)
			{
				switch(detectSite($link))
					{
						case 'youtube':
						$elink = youtube($link,str_replace(" ","-",$title));
							if($elink == 404) {
								echo "[Error] Video URL isn't valid!";  }
							else {
								echo $elink; }
					.
					.
					.
					.
					.
					.
					.
					.
					.
					.
					.
					.
						((More cases like above.))
					}
			}
		else
			{
				echo "[Error] Please write both: URL and title.";
			}
	} 
?>

 

And thank you again for being so helpful. :)

An alternate way (not better or worse):

 

Link# 1:  <input name="data[1][url]" size="80" type="text" /><br />
Title# 1: <input name="data[1][title]" size="80" type="text" /><br /><br />

Link# 2:  <input name="data[2][url]" size="80" type="text" /><br />
Title# 2: <input name="data[2][title]" size="80" type="text" /><br /><br />

 

foreach($_POST['data'] as $data) {
  echo $data['url'];
  echo $data['title'];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.