randomor
randomor

Reputation: 5663

PHP map named array to another named array

I have the following code for generating a new array:

$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language)
{
  return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
array_map('generateLanguageRules', $languages);

//Output:
array(
   0 => array(
     'seatsAllocatedForFrench' => 'numeric|max:300'
   ),
   1 => array(
     'seatsAllocatedForSpanish' => 'numeric|max:300'
   ),
   2 => array(
     'seatsAllocatedForGerman' => 'numeric|max:300'
   ),
   3 => array(
     'seatsAllocatedForChinese' => 'numeric|max:300'
   )
 )

I'm wondering if there is an easier way to output a flat array, instead of a nested one? I'm using Laravel. Are there maybe some helper functions that could do this?

UPDATE: One possible Laravel specific solution:

$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
$c = new Illuminate\Support\Collection($languages);
$c->map(function ($language){
  return ["seatsAllocatedFor$language"=>"numeric|max:300"];
})->collapse()->toArray();

Upvotes: 1

Views: 263

Answers (1)

user1978142
user1978142

Reputation: 7948

I dont know if laravel has a built-in method for that, (haven't used it yet). But alternatively, you could use RecursiveArrayIterator in conjunction to iterator_to_array() to flatten it and assign it. Consider this example:

$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language) {
    return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
$data = array_map('generateLanguageRules', $languages);
$data = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)));

echo "<pre>";
print_r($data);
echo "</pre>";

Sample Output:

Array
(
    [seatsAllocatedForFrench] => numeric|max:300
    [seatsAllocatedForSpanish] => numeric|max:300
    [seatsAllocatedForGerman] => numeric|max:300
    [seatsAllocatedForChinese] => numeric|max:300
)

Upvotes: 1

Related Questions