Core\Arr::flatten
Takes the arrays inside an array and gives you all their values as one flat array. It replaces the loop over the inner arrays you would otherwise write yourself.
Only one level is removed. The values come out in the order they were met, and an array inside an inner array stays an array. Core\Arr::flattenDeep is the member that removes every level.
The keys are gone, and the result is numbered from 0. Two inner arrays can hold the same key, so only one of them could have kept it. Every entry of the array has to be an array, and an inner array with no entries adds nothing to the result.
Parameters
$aarray<array<T>>An array of arrays.
Return value
Returns array<T>. A list renumbered from "0". The inner keys are discarded, because two inner arrays can have the same key.
Examples
One list from many
<?nvs// Shows how to make one list out of the arrays inside an array.
array<array<string>> $perDay = [ ['bread', 'milk'], ['apples'], [],];
// `Core\Arr::flatten` gives you the values of every inner array, in order.// This prints ["bread","milk","apples"].echo Core\Json::encode(Core\Arr::flatten($perDay)), "\n";
// An inner array with no entries adds nothing. This prints 3.echo Core\Arr::count(Core\Arr::flatten($perDay)), "\n";["bread","milk","apples"]3One level and the keys
<?nvs// Shows how much nesting is removed, and what happens to the keys.
array<array<string>> $byCity = [ 'berlin' => ['first' => 'Ada', 'second' => 'Bob'], 'lisbon' => ['first' => 'Alice'],];
// The keys of the inner arrays are gone and the result is numbered from 0, so// both "first" entries survive. This prints ["Ada","Bob","Alice"].echo Core\Json::encode(Core\Arr::flatten($byCity)), "\n";
array<array<array<string>>> $groups = [[['a'], ['b']], [['c']]];
// Only one level is removed, so the values of the result are still arrays.// This prints [["a"],["b"],["c"]].echo Core\Json::encode(Core\Arr::flatten($groups)), "\n";["Ada","Bob","Alice"][["a"],["b"],["c"]]The tags of every article
<?nvs// Shows how to collect the tags of several articles into one list.
array<array<string>> $tagsPerArticle = [ 'welcome' => ['news', 'intro'], 'release' => ['news', 'release'],];
array<string> $allTags = Core\Arr::flatten($tagsPerArticle);
// The list holds every tag, including the one two articles share. This prints// ["news","intro","news","release"].echo Core\Json::encode($allTags), "\n";
// `Core\Arr::flip` makes every tag a key, which gives you each of them once.// This prints ["news","intro","release"].echo Core\Json::encode(Core\Arr::keys(Core\Arr::flip($allTags))), "\n";["news","intro","news","release"]["news","intro","release"]