1

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();

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

$data = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($data))); That's genius and insanity. Thanks! Laravel specific solution: $c = new Illuminate\Support\Collection($languages); $c->map(function ($language){ return ["seatsAllocatedFor$language"=>"numeric|max:300"]; })->collapse()->toArray();
@randomor Your welcome, maybe you should also put an edit on your question regarding your specific laravel solution. This might help other laravel users too in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.