Reputation: 306
I have two arrays, one array in the code is representing title(simple string), and the other one is email(simple string also). This two arrays will always be the same, and I need to create key value pairs of them.
[
$email => $title
]
So, my $email array looks like this:
Array
(
[0] => [email protected]
[1] => [email protected]
[2] => [email protected]
)
And my $tile array looks like this:
Array
(
[0] => Distributor
[1] => Internal
[2] => Agency
)
So I need this two arrays to be:
Array
(
[[email protected]] => Distributor
[[email protected]] => Internal
[[email protected]] => Agency
)
In the beginning I was using the array_combine, but when this duplicated email values occurred my code broke. I could not find good solution at this point. I tried to manipulate the arrays with this function from the php manual:
function array_combine_($keys, $values)
{
$result = array();
foreach ($keys as $i => $k) {
$result[$k][] = $values[$i];
}
array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
return $result;
}
But it is deprecated and it does not work. I appreciate any help with this issue.
Upvotes: 0
Views: 43
Reputation: 6388
you cannot have multiple of the same key in an associative array.
You can use the values as the keys and keys as values
$keys = ['[email protected]','[email protected]','[email protected]'];
$values = ['Distributor','Internal','Agency'];
$res = array_combine($values, $keys);
Output
Array
(
[Distributor] => [email protected]
[Internal] => [email protected]
[Agency] => [email protected]
)
Or you can add something to make them unique like the index number and later on remove that index number
$keys = ['[email protected]','[email protected]','[email protected]'];
$values = ['Distributor','Internal','Agency'];
$res = [];
array_walk($keys, function($v, $k) use ($values, &$res){
$res[$v."-".$k] = $values[$k];
});
Output
Array
(
[[email protected]] => Distributor
[[email protected]] => Internal
[[email protected]] => Agency
)
Here you can remove the -Index to use them.
Upvotes: 2