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