/ Gists / PHP

Gists - PHP

On gists

Transaction via callback ;)

Nette PHP

example.php #

<?php

// https://forum.nette.org/cs/22304-zavislost-jednoho-modelu-na-jinych

	/**
	 * @param Closure $callback
	 */
	private function doInTransaction(Closure $callback)
	{
		$this->isInTransaction = TRUE;
		$callback();
		$this->isInTransaction = FALSE;
	}
	
	
	// usage
	// any class
	private $isInTransaction = FALSE;
	
	
	
	/**
	 * @param int $id
	 * @param Player $owner
	 */
	public function __construct($id, Player $owner)
	{
		$this->id = $id;
		$this->owner = $owner;

		$this->doInTransaction(function () use ($owner) {
			$owner->receiveItem($this);
		});
	}



	/**
	 * @param Player $newOwner
	 */
	public function changeOwner(Player $newOwner)
	{
		if ($this->owner !== $newOwner) {
		  $this->doInTransaction(function () use ($newOwner) {
				$this->owner->giveItem($this);
				$this->owner = $newOwner;
				$this->owner->receiveItem($this);
			});
		}
	}

On gists

Google Spread Sheet via Google_Client

PHP Libs PHP

index.php #

<?php
/*

https://www.nidup.io/blog/manipulate-google-sheets-in-php-with-api

*/

require './vendor/autoload.php'; 

// configure the Google Client
$client = new \Google_Client();
$client->setApplicationName('Google Sheets API');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]); 
$client->setAccessType('offline');
// credentials.json is the key file we downloaded while setting up our Google Sheets API
$path = '***'; //google console admin need to generate this file
$client->setAuthConfig($path);

// configure the Sheets Service
$service = new \Google_Service_Sheets($client);
$spreadsheetId = '***'; // get with share with and see to url



// the spreadsheet id can be found in the url https://docs.google.com/spreadsheets/d/143xVs9lPopFSF4eJQWloDYAndMor/edit
$spreadsheet = $service->spreadsheets->get($spreadsheetId);
var_dump($spreadsheet);


// all values
$range = 'List 1'; // here we use the name of the Sheet to get all the rows
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
var_dump($values);



// rows by range
$range = 'List 1!A1:F10';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
var_dump($values);



// cells of column
$range = 'List1!B1:B21'; // the column containing the movie title
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
var_dump($values);



// rows into json objects
$range = 'Sheet1';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$rows = $response->getValues();
// Remove the first one that contains headers
$headers = array_shift($rows);
// Combine the headers with each following row
$array = [];
foreach ($rows as $row) {
    $array[] = array_combine($headers, $row);
}
var_dump($array);
/*
$jsonString = json_encode($array, JSON_PRETTY_PRINT);
print($jsonString);

*/


// append new row
$newRow = [
    '456740',
    'Hellboy',
    'https://image.tmdb.org/t/p/w500/bk8LyaMqUtaQ9hUShuvFznQYQKR.jpg',
    "Hellboy comes to England, where he must defeat Nimue, Merlin's consort and the Blood Queen. But their battle will bring about the end of the world, a fate he desperately tries to turn away.",
    '1554944400',
    'Fantasy, Action'
];
$rows = [$newRow]; // you can append several rows at once
$valueRange = new \Google_Service_Sheets_ValueRange();
$valueRange->setValues($rows);
$range = 'List 1'; // the service will detect the last row of this sheet
$options = ['valueInputOption' => 'USER_ENTERED'];
$service->spreadsheets_values->append($spreadsheetId, $range, $valueRange, $options);



// update existing
$updateRow = [
    '456740',
    'Hellboy Updated Row',
    'https://image.tmdb.org/t/p/w500/bk8LyaMqUtaQ9hUShuvFznQYQKR.jpg',
    "Hellboy comes to England, where he must defeat Nimue, Merlin's consort and the Blood Queen. But their battle will bring about the end of the world, a fate he desperately tries to turn away.",
    '1554944400',
    'Fantasy, Action'
];
$rows = [$updateRow];
$valueRange = new \Google_Service_Sheets_ValueRange();
$valueRange->setValues($rows);
$range = 'Sheet1!A2'; // where the replacement will start, here, first column and second line
$options = ['valueInputOption' => 'USER_ENTERED'];
$service->spreadsheets_values->update($spreadsheetId, $range, $valueRange, $options);



// delete some row
$range = 'Sheet1!A23:F24'; // the range to clear, the 23th and 24th lines
$clear = new \Google_Service_Sheets_ClearValuesRequest();
$service->spreadsheets_values->clear($spreadsheetId, $range, $clear);


/** with text formatting */
$range = 'List 1!B4';
$params = [
    'ranges' => $range,
    'fields' => 'sheets.data.rowData.values',
    'includeGridData' => true,
];

$response = $service->spreadsheets->get($spreadsheetId, $params);
$data = $response->getSheets()[0]['data'][0]['rowData'][0]['values'][0];

$formattedValue = $data['formattedValue'];
$hyperlink = $data['hyperlink'];
$userEnteredFormat = $data['userEnteredFormat'];

var_dump($formattedValue);
var_dump($hyperlink);
var_dump($userEnteredFormat);

On gists

Delete recursively from child to parent

PHP AW

delete-recursively-from-child.ph #

<?php

	private function deleteDuplicateRecursive(Tables\Navigation $duplicateItem)
	{
		/*
		// OLD
		$findDescendants = function(Tables\Navigation $parent, array $stack = [], $level = 1) use (&$findDescendants) {
			$children = $this->navigation->getAdjacencyList($parent->domain_id)->getChildren($parent->id);
			
			foreach ($children as $child) {
				$stack[$level][] = $child;
				$stack = $findDescendants($child, $stack, $level + 1);
			} 
				
			return $stack;
		};

		// mazeme deti odspoda nahoru
		$descendants = $findDescendants($duplicateItem);

		foreach (array_reverse($descendants, true) as $level => $descendantArr) {
			foreach ($descendantArr as $descendant) {
				$this->deleteDuplicate($descendant);
			}
		}
		*/

    // NEW, better, shorter
		$children = $this->navigation->getAdjacencyList($duplicateItem->domain_id)->getChildren($duplicateItem->id);
		foreach ($children as $child) {
			$this->deleteDuplicateRecursive($child);
		}

		// na zaver i roota
		$this->deleteDuplicate($duplicateItem);
	}

On gists

Normalizace dat

PHP AW

normalizace.php #

<?php 

// 1) single fns ..

$data = [
    '400,22 je super cislo a neobsahuje ani @',
    'Symbol @ je bezvič',
    '@@@ nebo XXX?',
    'Tady nic',
];

$NaNicToNeplati = function() {
    return null;
};

$NumberDashToDot = function($value) {
    if (preg_match('~\d+,\d+~', $value)) {
        return str_replace(',', '.', $value);
    }

    return null;
};

$RemoveZavinac = function($value) {
    if (preg_match('~@~', $value)) {
        return str_replace('@', '', $value);
    }

    return null;
};

$RemoveXXX = function($value) {
    if (preg_match('~X~', $value)) {
        return str_replace('X', 'maleX', $value);
    }

    return null;
};

$filters = [
    'NumberDashToDot' => $NumberDashToDot,
    'NaNicToNeplati' => $NaNicToNeplati,
    'RemoveZavinac' => $RemoveZavinac,
    'RemoveXXX' => $RemoveXXX,
];


 $evaluate = function($data, $filters) {
    $results = [];
    foreach ($data as $value) {
        $origValue = $value;
        $result = [
            'met' => [],
            'notMet' => [],
            'transformations' => [],
            'origValue' => $value,
            'finalValue' => null,
        ];

        foreach ($filters as $fnName => $fnClosure) {
            if ($valueNormalized = $fnClosure($value)) {
                $value = $valueNormalized;
                
                $result['met'][] = $fnName;
                $result['transformations'][$fnName] = $valueNormalized;
            } else {
                $result['notMet'][] = $fnName;
            }
        }

        
        $result['finalValue'] = $value;

        $results[] = $result;
    }

    return $results;

};

$results = $evaluate($data, $filters);

echo "<pre>";
print_r($results);
echo "</pre>";



// OOP
class DataTransformer
{
    private $filters;

    public function __construct(array $filters)
    {
        $this->filters = $filters;
    }

    public function transform(array $data): array
    {
        return array_map(function ($value) {
            $result = [
                'met' => [],
                'notMet' => [],
                'transformations' => [],
                'origValue' => $value,
                'finalValue' => null,
            ];

            foreach ($this->filters as $filter) {
                if ($filter->apply($value)) {
                    $result['met'][] = $filter->getName();
                    $result['transformations'][$filter->getName()] = $value;
                } else {
                    $result['notMet'][] = $filter->getName();
                }
            }

            $result['finalValue'] = $value;

            return $result;
        }, $data);
    }
}

interface FilterInterface
{
    public function apply(string &$value): bool;
    public function getName(): string;
}

class NumberDashToDotFilter implements FilterInterface
{
    public function apply(string &$value): bool
    {
        if (preg_match('~\d+,\d+~', $value)) {
            $value = str_replace(',', '.', $value);
            return true;
        }

        return false;
    }

    public function getName(): string
    {
        return 'NumberDashToDot';
    }
}

class RemoveZavinacFilter implements FilterInterface
{
    public function apply(string &$value): bool
    {
        if (strpos($value, '@') !== false) {
            $value = str_replace('@', '', $value);
            return true;
        }

        return false;
    }

    public function getName(): string
    {
        return 'RemoveZavinac';
    }
}

// Přidat další filtry podle potřeby

$data = [
    '400,22 je super cislo a neobsahuje ani @',
    'Symbol @ je bezvič',
    '@@@ nebo XXX?',
    'Tady nic',
];

$filters = [
    new NumberDashToDotFilter(),
    new RemoveZavinacFilter(),
    // Přidat další filtry podle potřeby
];

$transformer = new DataTransformer($filters);
$results = $transformer->transform($data);

echo "<pre>";
print_r($results);

On gists

Faster way than isset

PHP tricks - one liners PHP

isset.php #

<?php

/*
  if (isset($a['b'])) {
    $x = $a['b'];
    echo $x;
  }

*/

if ($x = ($a['b'] ?? null)) {
    echo $x;
}

On gists

Collection (filter, map, sort ... in one)

PHP Libs PHP

Collection.php #

<?php

/* https://betterprogramming.pub/how-to-make-your-php-code-beautiful-with-chainable-methods-83d8832b1b16 */

class Collection
{
    private $array;
    public function __construct($array)
    {
        $this->array = $array;
    }
    public function filter($callback)
    {
        $this->array = array_filter($this->array, $callback);
        return $this;
    }
    public function map($callback)
    {
        $this->array = array_map($callback, $this->array);
        return $this;
    }
    public function sort($callback)
    {
        usort($this->array, $callback);
        return $this;
    }
    public function execute()
    {
        return $this->array;
    }
}


$characters = new Collection([
    'Maggie Simpson',
    'Edna Krabappel',
    'Marge Simpson',
    'Lisa Simpson',
    'Moe Szyslak',
    'Waylon Smithers',
    'Homer Simpson',
    'Bart Simpson'
]);
$simpsons = $characters
    ->filter(function ($character) {
        return preg_match('/^.+\sSimpson$/', $character);
    })
    ->map(function ($character) {
        return str_replace(' Simpson', '', $character);
    })
    ->sort(function ($a, $b) {
        return strcasecmp($a, $b);
    })
    ->execute();
var_dump($simpsons); // ['Bart', 'Homer', 'Lisa', 'Maggie', 'Marge']

On gists

Kometa comments - more ways to refactor

Refactoring PHP

comments.php #

<?php

//  if hell
if ($commentRow->type == 'forum')
{
    $baseUrl = '/diskuse';
}

if ($commentRow->type == 'clanek')
{
    $baseUrl = '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
}

if ($commentRow->type == 'zapas')
{
    $baseUrl = '/zapas/' .  $commentRow->rellID;
}

if ($commentRow->type == 'stranka')
{
    $baseUrl = '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
}

\Redirect::url($baseUrl .'?l='.$newPageNo.'&parentNode='.$commentRow->parent_sibling_id.'#cmt-'.$commentRow->id);


// map table
$baseUrlMap = [
    'forum' => '/diskuse',
    'clanek' => '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID),
    'zapas' => '/zapas/' .  $commentRow->rellID,
    'stranka' => '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID),
];

$baseUrl = '';

if (isset($baseUrlMap[$commentRow->type])) {
    $baseUrl = $baseUrlMap[$commentRow->type];
}



// 3 callback fns
$baseUrlMap = [
    'forum' => '/diskuse',
    'clanek' => function() use ($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    },
    'zapas' => function() use ($commentRow) {
        return '/zapas/' . $commentRow->rellID;
    },
    'stranka' => function() use ($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    },
];

$baseUrl = '';

if (isset($baseUrlMap[$commentRow->type])) {
    if (is_callable($baseUrlMap[$commentRow->type])) {
        $baseUrl = $baseUrlMap[$commentRow->type]();
    } else {
        $baseUrl = $baseUrlMap[$commentRow->type];
    }
}



// Factories

$baseUrl = '';

interface UrlGenerator {
    public function generateUrl($commentRow);
}

class ForumUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/diskuse';
    }
}

class ClanekUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class ZapasUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/zapas/' .  $commentRow->rellID;
    }
}

class StrankaUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

$generators = [
    'forum' => new ForumUrlGenerator(),
    'clanek' => new ClanekUrlGenerator(),
    'zapas' => new ZapasUrlGenerator(),
    'stranka' => new StrankaUrlGenerator(),
];

$commentType = $commentRow->type;
if (isset($generators[$commentType])) {
    $baseUrl = $generators[$commentType]->generateUrl($commentRow);
}


// fns for all with argument
$baseUrlMap = [
    'forum' => function($row) {
        return '/diskuse';
    },
    'clanek' => function($row) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $row->rellID);
    },
    'zapas' => function($row) {
        return '/zapas/' .  $row->rellID;
    },
    'stranka' => function($row) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $row->rellID);
    },
];

$commentType = $commentRow->type;
if (isset($baseUrlMap[$commentType])) {
    $baseUrl = $baseUrlMap[$commentType]($commentRow);
}



// FactoryGenerator

interface UrlGenerator {
    public function generateUrl($commentRow);
}

class ForumUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/diskuse';
    }
}

class ClanekUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class ZapasUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/zapas/' .  $commentRow->rellID;
    }
}

class StrankaUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class UrlGeneratorFactory {
    public static function createGenerator($type): UrlGenerator {
        $generators = [
            'forum' => new ForumUrlGenerator(),
            'clanek' => new ClanekUrlGenerator(),
            'zapas' => new ZapasUrlGenerator(),
            'stranka' => new StrankaUrlGenerator(),
        ];

        return $generators[$type] ?? null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}


// Dalsi o neco lepsi
class UrlGeneratorFactory {
    public static function createGenerator($type): ?UrlGenerator {
        $generators = [
            'forum' => function () {
                return new ForumUrlGenerator();
            },
            'clanek' => function () {
                return new ClanekUrlGenerator();
            },
            'zapas' => function () {
                return new ZapasUrlGenerator();
            },
            'stranka' => function () {
                return new StrankaUrlGenerator();
            },
        ];

        return $generators[$type] ? $generators[$type]() : null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}



// Moje verze, lazy, nejefektivnejsi

class UrlGeneratorFactory {
    public static function createGenerator($type): ?UrlGenerator {
        $generators = [
            'forum' => ForumUrlGenerator::class,
            'clanek' => ClanekUrlGenerator::class,
            'zapas' => ZapasUrlGenerator::class,
            'stranka' => StrankaUrlGenerator::class,
        ];

        if (isset($generators[$type])) {
            return new $generators[$type]();
        }

        return null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}




// Claude 3.5
// Strategy pattern
<?php

interface CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string;
}

class ForumRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/diskuse';
    }
}

class ArticleRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class MatchRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/zapas/' . $commentRow->rellID;
    }
}

class PageRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class CommentRedirectHandler {
    private array $strategies = [];

    public function addStrategy(string $type, string $strategyClass): void {
        if (!is_subclass_of($strategyClass, CommentRedirectStrategy::class)) {
            throw new \InvalidArgumentException("$strategyClass musí implementovat CommentRedirectStrategy");
        }
        $this->strategies[$type] = $strategyClass;
    }

    public function redirect(object $commentRow, int $newPageNo): void {
        if (!isset($this->strategies[$commentRow->type])) {
            throw new \InvalidArgumentException("Neznámý typ komentáře: {$commentRow->type}");
        }

        $strategyClass = $this->strategies[$commentRow->type];
        $strategy = new $strategyClass(); // Vytvoření instance až když je potřeba
        $baseUrl = $strategy->getBaseUrl($commentRow);

        $redirectUrl = sprintf(
            '%s?l=%d&parentNode=%d#cmt-%d',
            $baseUrl,
            $newPageNo,
            $commentRow->parent_sibling_id,
            $commentRow->id
        );

        \Redirect::url($redirectUrl);
    }
}

// Použití:
$handler = new CommentRedirectHandler();
$handler->addStrategy('forum', ForumRedirectStrategy::class);
$handler->addStrategy('clanek', ArticleRedirectStrategy::class);
$handler->addStrategy('zapas', MatchRedirectStrategy::class);
$handler->addStrategy('stranka', PageRedirectStrategy::class);

// Při zpracování komentáře:
$handler->redirect($commentRow, $newPageNo);




// slozitejsi vic tovaren
<?php

interface CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string;
}

class ForumRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/diskuse';
    }
}

class ArticleRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class MatchRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/zapas/' . $commentRow->rellID;
    }
}

class PageRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class CommentRedirectStrategyFactory {
    private array $strategies = [
        'forum' => ForumRedirectStrategy::class,
        'clanek' => ArticleRedirectStrategy::class,
        'zapas' => MatchRedirectStrategy::class,
        'stranka' => PageRedirectStrategy::class,
    ];

    public function createStrategy(string $type): CommentRedirectStrategy {
        if (!isset($this->strategies[$type])) {
            throw new \InvalidArgumentException("Neznámý typ komentáře: {$type}");
        }

        $strategyClass = $this->strategies[$type];
        return new $strategyClass();
    }
}

class CommentRedirectHandler {
    private CommentRedirectStrategyFactory $factory;

    public function __construct(CommentRedirectStrategyFactory $factory) {
        $this->factory = $factory;
    }

    public function redirect(object $commentRow, int $newPageNo): void {
        $strategy = $this->factory->createStrategy($commentRow->type);
        $baseUrl = $strategy->getBaseUrl($commentRow);

        $redirectUrl = sprintf(
            '%s?l=%d&parentNode=%d#cmt-%d',
            $baseUrl,
            $newPageNo,
            $commentRow->parent_sibling_id,
            $commentRow->id
        );

        \Redirect::url($redirectUrl);
    }
}

// Použití:
$factory = new CommentRedirectStrategyFactory();
$handler = new CommentRedirectHandler($factory);

// Při zpracování komentáře:
$handler->redirect($commentRow, $newPageNo);

On gists

lambda usort sorting

PHP

sort.php #

<?php
$x = [
	[
		'name' => 'BBB',
		'pts' => 30,
	],
	[
		'name' => 'AAA',
		'pts' => 90,
	],
	[
		'name' => 'CCC',
		'pts' => 40,
	]
];

usort($x, sortBy('pts', 'DESC')); // Změna zde - přidán parametr pro směr řazení

function sortBy($k, $sortOrder = 'ASC') // Změna zde - přidán druhý parametr s výchozí hodnotou ASC
{
	return function($a, $b) use ($k, $sortOrder)
	{
		$result = $a[$k] <=> $b[$k];
		return ($sortOrder === 'ASC') ? $result : -$result; // Změna zde - záporná hodnota pro DESC řazení
	};
}

echo "<pre>";
print_r($x);



//  2 way


function customSort($a, $b, $key, $sortOrder) {
    return $sortOrder === 'ASC' ? ($a[$key] <=> $b[$key]) : ($b[$key] <=> $a[$key]);
}

$key = 'name'; // Změňte podle sloupce, podle kterého chcete řadit
$sortOrder = 'ASC'; // Změňte na 'DESC' pro sestupné řazení

usort($x, function($a, $b) use ($key, $sortOrder) {
    return customSort($a, $b, $key, $sortOrder);
});

echo "<pre>";
print_r($x);

On gists

array_walk_recursive

PHP

demo.php #

<?php

$data = array(
    array('id' => 1, 'name' => 'John', 'children' => array('Alice', 'Bob')),
    array('id' => 2, 'name' => 'Jane', 'children' => array('Charlie', 'David')),
);

function add_last_name(&$value, $key) {
    if ($key === 'name') {
        $value .= ' Doe';
    }
}

array_walk_recursive($data, 'add_last_name');

print_r($data);

/*

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John Doe
            [children] => Array
                (
                    [0] => Alice Doe
                    [1] => Bob Doe
                )
        )
    [1] => Array
        (
            [id] => 2
            [name] => Jane Doe
            [children] => Array
                (
                    [0] => Charlie Doe
                    [1] => David Doe
                )
        )
)


*/

On gists

PHP nested value in multi array with own separator

PHP Libs PHP

fn.php #

<?php

function getNestedValue($array, $path, $separator = '.') {
    $keys = explode($separator, $path);
    
    foreach ($keys as $key) {
        if (isset($array[$key])) {
            $array = $array[$key];
        } else {
            return null; // nebo hodnotu podle vašich potřeb
        }
    }
    
    return $array;
}


$x = [
    'a' => [
        'b' => [
            'c' => 'FINAL C ... ;)'
        ],
    ],
];

echo getNestedValue($x, 'a.b.c');