andydune/array-walker

Better implementation foreach operator with nested array compability.

v1.0.0 2018-05-18 08:21 UTC

This package is auto-updated.

Last update: 2024-10-29 04:53:32 UTC


README

Build Status Software License Packagist Version Total Downloads

Better implementation foreach operator with nested array compability.

Installation

Installation using composer:

composer require andydune/array-walker

Or if composer was not installed globally:

php composer.phar require andydune/array-walker

Or edit your composer.json:

"require" : {
     "andydune/array-walker": "^1"
}

And execute command:

php composer.phar update

Example

use AndyDune\ArrayWalker\ArrayWalker;
use AndyDune\ArrayWalker\ItemContainer;

// Source array
$array = [
    'one' => 1,
    'two' => 2,
    'three' => 3,
];

$arrayWalker = new ArrayWalker($array);
// Change values
$arrayWalker->addFunction(function (ItemContainer $item) {
    $item->setValue($item->getValue() + 10);
});
$result = $arrayWalker->apply();
$result = [
    'one' => 11,
    'two' => 12,
    'three' => 13,
];

$arrayWalker = new ArrayWalker($array);
// Change keys
$arrayWalker->addFunction(function (ItemContainer $item) {
   $item->setKey(strtoupper($item->getKey()));
});
$result = $arrayWalker->apply();
$result = [
    'ONE' => 1,
    'TWO' => 2,
    'THREE' => 3,
];

$arrayWalker = new ArrayWalker($array);
// Delete value 
$arrayWalker = new ArrayWalker($array);
$arrayWalker->addFunction(function (ItemContainer $item) {
    $item->setValue($item->getValue() + 10);
    if ($item->getKey() == 'one') {
        $item->delete();
    }
});
$result = $arrayWalker->apply();

$result = [
    'two' => 12,
    'three' => 13,
];