Novactive / NovaCollection

Collection implementation that wraps regular PHP arrays.
MIT License
9 stars 3 forks source link

reindex with callback #15

Open nozavroni opened 7 years ago

nozavroni commented 7 years ago

As far as I know, there is no way to re-index a collection using a callback. This is something I often need and don't have. In ANY collection library. I don't think I've ever seen it.

$coll = Factory::create([
   'one' => 1,
   'two' => 2,
   'three' => 'little pigs'
]);

$newcoll = $coll->reindex(function($val, $key) {
    if (is_numeric($val)) return $val;
    return $key;
});

// $newcoll now contains... 
[
    1 => 1,
    2 => 2,
    'three' => 'little pigs'
]

key AND value would be nice too...

$newcoll = $coll->morph(function($val, $key) {
    $newkey = $key . '_morphed';
    $newval = $key . '_' . $val;
    return [$newkey, $newval];
});
// newcoll should now contain...
[
    'one_morphed' => 'one_1',
    'two_morphed' => 'two_2',
    'three_morphed' => 'three_little pigs'
]
anaelChardan commented 7 years ago

It's mapKeys :-)