user2572858 user2572858 - 2 months ago 7
PHP Question

Looking up data in one array to build another array

I have an array like this....

$interests = ['f13d6415ed' => 'Mailing', 'a6e5730911' => 'Friend-Family', '998f2252f5' => 'Friend-Patron', '6873081334' => 'Adult', '89c4c64d51' => 'Non-Acting', 'ea325784ac' => 'Life', '8ffdecd43d' => 'Youth Theatre', '6752d0543e' => 'Young Person',];


... and I need to end up building an array like this (used in an api call)...

'interests' => ['f13d6415ed'=>false, 'a6e5730911'=>false, '998f2252f5'=>false, '6873081334'=>true, '89c4c64d51'=>false, 'ea325784ac'=>false, '8ffdecd43d'=>false, '6752d0543e'=>false ],


So I can do an array_search() on the first array (given the text term) and get the key needed. Then I need to build the second array where the data for the given key (there will only be one) is 'true' and all others are 'false'. This second array is part of the parameters of an api call (Mailchimp).
I can see a few ways to do it but I'm not a php expert and they all seem very messy. Any suggestions?

Thanks

Answer

The solution using array_fill_keys and array_keys functions:

$interests = ['f13d6415ed' => 'Mailing', 'a6e5730911' => 'Friend-Family', '998f2252f5' => 'Friend-Patron', '6873081334' => 'Adult', '89c4c64d51' => 'Non-Acting', 'ea325784ac' => 'Life', '8ffdecd43d' => 'Youth Theatre', '6752d0543e' => 'Young Person',];

$new_arr = [];
$keyTrue = '6873081334';
$new_arr['interests'] = array_fill_keys(array_keys($interests), false);
$new_arr['interests'][$keyTrue] = true;

var_dump($new_arr);
Comments