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)

 

Link to comment
Share on other sites

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);
?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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)
Link to comment
Share on other sites

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
)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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;


}


?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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. :)

Link to comment
Share on other sites

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'];
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.