lundi 11 avril 2016

Keys and Values re-formatting in PHP

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire