Skip to content

Instantly share code, notes, and snippets.

@stipic
Last active January 10, 2021 14:50
Show Gist options
  • Save stipic/33e050a261990c904d94a44b9e48e36e to your computer and use it in GitHub Desktop.
Save stipic/33e050a261990c904d94a44b9e48e36e to your computer and use it in GitHub Desktop.
Recursive array by array walk PHP
<?php
declare(strict_types=1);
namespace App\Service\Walker;
/**
* @author Kristijan Stipić 03092019
*/
class Walker
{
/**
* @author Kristijan Stipić 03092019
* @param [type] $arr
* @param \closure $manipulator
* @return void
*/
static public function array_recursive_walk_by_object(&$arr, \closure $manipulator) : void
{
if(\is_array($arr))
{
foreach($arr as $key => &$value)
{
$parent = &$arr[$key];
if(\is_array($value) && !empty($value))
{
/**
* @param $key string
* @param $value array
* @param $parent array
*/
$manipulator($key, $value, $parent);
self::array_recursive_walk_by_object($value, $manipulator);
}
}
}
}
}
// Example:
$content = [
'test' => [
'key' => 'value',
'key2' => 'value2',
'key3' => [
'key3.1' => 'value3.1'
]
]
];
$arr = 'nothing special';
Walker::array_recursive_walk_by_object($content, function($key, &$value, &$parent) use($arr)
{
if(isset($value['key3']) && is_array($value['key3']))
{
$value['key3'] = [
'key3.1-changed' => 'value3.1-changed'
];
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment