PHP turn array of multivalue arrays into single layer array with multiple keys going to one value each
array_flip
for multidimensional array
Trying to go from an array with one key each going to many values (so an array of arrays) to each value becoming a key that goes to exactly one value (that had been the key), but these can be repeated.
So:
$culinary_categories = [
'fruit' => ['apple', 'banana', 'orange'],
'vegetable' => ['onion', 'spinach', 'zucchini'],
];
becomes:
[
'apple' => 'fruit',
'banana' => 'fruit'
'orange' => 'fruit'
'onion' => 'vegetable'
'spinach' => 'vegetable'
'zucchini' => 'vegetable'
]
Could also call this creating a denormalized array?
Anyway this code does it:
foreach ($one_key_to_many_values as $valid => $accepted) {
foreach ($accepted as $input) {
$names[strtolower($input)] = $valid;
}
}
Full example with a use case:
<?php
class WaitlistStatusImporter extends ImporterBase {
public static $fieldNameMap = [
'household_waitlist.field_household' => ['Client Nid', 'Client'], // References Client Household `household`
'household_waitlist.field_waitlist' => ['Waitlist Nid', 'Waitlist'], // References Program: Waitlist `waitlist`
'household_waitlist.field_lottery_number' => ['Lottery Number', 'lottery #', 'lottery num', 'lotterynumber', 'lotterynum'],
'individual.field_first_name' => ['First name', 'Firstname', 'First'],
'individual.field_middle_name' => ['Middle name', 'Middlename', 'Middle'],
];
public static function acceptedToValidFieldNames() {
static $names = [];
if ($names) {
return $names;
}
foreach (self::$fieldNameMap as $valid => $accepted) {
foreach ($accepted as $input) {
$names[strtolower($input)] = $valid;
}
}
return $names;
}
public static function convertFieldNames($names) {
$new_names = [];
foreach ($names as $name) {
$new_names[] = self::acceptedToValidFieldNames()[strtolower($name)] ?? $name;
}
return $new_names;
}
}