1

How do I combine two arrays where the first array contains duplicate keys? e.g. combine the following:

$keys_arr
Array
    (
        [0] => iPhone
        [1] => iPhone
        [2] => iPhone
        [3] => Samsung
    )

$values_arr
Array
(
    [0] => 5
    [1] => 5
    [2] => 5
    [3] => Galaxy IV
)

The result I'm looking for is:

$combined_array
Array
    (
        [iPhone] => 5
        [iPhone] => 5
        [iPhone] => 5
        [Samsung] => Galaxy IV
    )

Using the following foreach (PHP - merge two arrays similar to array_combine, but with duplicate keys):

foreach ($keys_arr as $key => $value) {
    $combined_array[] = array($value => $values_arr[$key]);
}

I get:

Array
(
    [0] => Array
        (
            [iPhone] => 5
        )

    [1] => Array
        (
            [iPhone] => 5
        )

    [2] => Array
        (
            [iPhone] => 5
        )

    [3] => Array
        (
            [Samsung] => Galaxy IV
        )

)

Where am I going wrong?

5
  • 7
    The result you're looking for is not possible because PHP doesn't allow duplicate keys in an array Commented Feb 28, 2014 at 19:15
  • Why not try creating $combined_array = array(array('iPhone', '5'), array('iPhone' ,'5'), array('iPhone' ,'5'), array('Samsung' ,'Galaxy IV') ); Commented Feb 28, 2014 at 19:17
  • So it looks like you are combining two pieces of information about a single object together. You might consider combining to an array of objects like [{'product_line':'iPhone', 'model': '5'}, ... , {'product_line':'Samsung','model': 'Galaxy IV'}] such that you create a new property name for each of the array values by which you can definitively lookup the information you are trying to store. Commented Feb 28, 2014 at 19:19
  • $combined_array[] = ... will add a new element (which happens to be an array) to $combined_array. Commented Feb 28, 2014 at 19:25
  • @MarkBaker Thanks, I (stupidly) had no idea array keys had to be unique! Commented Feb 28, 2014 at 19:26

1 Answer 1

0

php's associative arrays need to have unique keys for values - while you can have values that are all the same (i.e: 5, 5, 5), the keys MUST be distinct.

One way you can "work around" this is by using a Linked List data structure in the case of duplicates; this would result in;

$iPhone = {(5), (5), (5)}

$Samsung = Galaxy IV

An easy workaround to accomplish this would be to use a multi-dimensional array; i.e:

Array[iPhone] would hold a seperate array, containing {5, 5, 5}.

You can read up more on actual linked lists here; http://www.php.net/manual/en/class.spldoublylinkedlist.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.