Skip to content

Instantly share code, notes, and snippets.

@MkLHX
Last active March 25, 2020 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MkLHX/e8f8346ceadcc29d1c7f8767e6e877ca to your computer and use it in GitHub Desktop.
Save MkLHX/e8f8346ceadcc29d1c7f8767e6e877ca to your computer and use it in GitHub Desktop.
How to update specific key on existing multidimensional array in twig
{% 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)}}
<?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