Reputation: 3323
Please read the whole question before attempting to answer. If I have two associative arrays where some values match just once:
$array1 = ['key1' => 'value1', 'key3' => 'value2', etc...];
$array2 = ['key2' => 'value1', 'key4' => 'value2', etc...];
but $array2 is longer than $array 1, and in those cases the keys don't have values:
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
Then how can I combine them to get the following result:
$array3 = [
'value1' => [$myconstant => key2],
'value2' => [$myconstant => key4],
'value3' => [$myconstant => ''],
etc...];
Notice that in cases where there is no match, an empty string is used instead of the key in the embedded associative array. In fact, the only reason why $array1 is necessary is because I need to know when there is a match with $array2 to get the correct format.
The values will not repeat themselves along the etc... chain.
I'm using Laravel and am trying to use Collections, but basic PHP solutions are okay too. Thank you very much.
Upvotes: 1
Views: 75
Reputation: 333
<?php
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
function x (array $a= array(), array $b = array()) {
$array = array();
$index = new ArrayObject($a);
$seed = new ArrayObject($b);
$a_it = $index->getIterator();
$b_it = $seed->getIterator();
while ($a_it->valid()) {
$x = $a_it->current();
$y = ($b_it->valid()) ? $b_it->current() : NULL;
if ($y !== NULL) {
# there is a value to compare against
if ($x === $y) {
$array["{$x}"] = array('myConst'=>$a_it->key());
}
$b_it->next();
} else {
# there is no value to compare against
$array["{$x}"] = array('myConst'=> '');
}
$a_it->next();
}
return $array;
}
$read = x($array2, $array1);
print_r($read);
Upvotes: 1
Reputation: 557
I guess the biggest hurdle you have is how to transform those values in keys and keys into values. array_flip is the answer to that problem. Once you have that, you can solve your problem with a simple foreach loop.
$myconstant = 'foo';
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
// array_flip switches keys and values in an array
$flip1 = array_flip($array1);
$flip2 = array_flip($array2);
$array3 = [];
foreach($flip2 as $key => $value) {
if(!isset($flip1[$key])) {
$array3[ $key ] = [ $myconstant => '' ];
} else {
$array3[ $key ] = [ $myconstant => $value ];
}
}
Laravel Collections have a flip() method, too. That might help you translating the script into Laravel.
Upvotes: 1