Last active
March 25, 2020 15:16
-
-
Save MkLHX/e8f8346ceadcc29d1c7f8767e6e877ca to your computer and use it in GitHub Desktop.
How to update specific key on existing multidimensional array in twig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% set contents = {"one": 1,"two":2,"three":3,"four":4,"five":5} %} | |
{# Create the array an structure somewhere in the view #} | |
{% set twigArray = {} %} | |
{% for content in contents %} | |
{% set twigArray = twigArray|merge({('hashkey_'~loop.index0):{'enabled':true,'caption':'unknow','button':{'text':'unknow','href':'unknow'},'image':{'src': content.content|raw),'alt':"image-"~loop.index, 'href':"" }}}) %} | |
{% endfor %} | |
{{ dump(twigArray)}} | |
{# For any reason you need to update a specific key value in the exiting array in the view | |
call the twig extension to do that in php side #} | |
{# in this example otherContents have the same length than contents #} | |
{% set otherContents = {"one": 1,"two":4,"three":9,"four":16,"five":25} %} | |
{% for otherContent in otherContents %} | |
{% set twigArray = twigArray|merge({('hashkey'~loop.index0):editArrayByHashKey(twigArray[('slide_'loop.index0)], 'five', otherContent)}) %} | |
{% endfor %} | |
{{ dump(twigArray)}} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Twig; | |
use Twig\Extension\AbstractExtension; | |
use Twig\TwigFunction; | |
class twigExt extends AbstractExtension | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getFunctions(): array | |
{ | |
return [ | |
new TwigFunction('editArrayByHashKey', [$this, 'editArrayByHashKey']), | |
]; | |
} | |
/** | |
* @param array $array | |
* @param $key | |
* @param $value | |
* @return array | |
*/ | |
public function editArrayByHashKey($array, $key, $value) | |
{ | |
$array[$key] = $value; | |
return $array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment