Skip to content

Instantly share code, notes, and snippets.

@jenswittmann
Last active August 21, 2020 14:54
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 jenswittmann/d936aed4d756b0d6baf9523bf270fcf6 to your computer and use it in GitHub Desktop.
Save jenswittmann/d936aed4d756b0d6baf9523bf270fcf6 to your computer and use it in GitHub Desktop.
loopJSON (MODX Snippet)
<?php
/**
* loopJSON
*
* DESCRIPTION
*
* This Snippet loop a JSON Array.
*
* PROPERTIES:
*
* &data required json_array
* &tpl required
* &sortby optional
* &sortdir optional
* &outputSeparator optional
*
* USAGE:
*
* [[loopJSON:before=`<ul>`:after=`</ul>`?
* &data=`{"name":"item1"},{"name":"item2"}`
* &tpl=`@CODE: <li>[[+idx]]: [[+name]]</li>` ]]
*
*/
# vars
$inlineTplPrefix = '@CODE:';
$rawData = $modx->getOption( 'data', $scriptProperties, false );
$data = json_decode( $rawData, true );
$tpl = $modx->getOption( 'tpl', $scriptProperties, $inlineTplPrefix . ' ' );
$sortby = $modx->getOption( 'sortby', $scriptProperties, false );
$sortdir = $modx->getOption( 'sortdir', $scriptProperties, 'ASC' );
$outputSeparator = $modx->getOption( 'outputSeparator', $scriptProperties, '' );
$locale = $modx->getOption( 'locale' );
$output = [];
if ( !is_array( $data ) ) return;
# sort
if ( $sortby ) {
$collator = new Collator( $locale );
uasort( $data, function( $a, $b ) use ( $collator, $sortby ) {
return $collator->compare( $a[ $sortby ], $b[ $sortby ] );
} );
}
if ( $sortdir == 'DESC' ) {
$data = array_reverse( $data );
}
# return data
if ( substr( $tpl, 0, strlen( $inlineTplPrefix ) ) == $inlineTplPrefix ) {
$chunk = $modx->newObject( 'modChunk', [
'name' => '{tmp}-{' . uniqid() . '}'
] );
$chunk->setCacheable(false);
$tpl = str_replace( $inlineTplPrefix, '', $tpl );
foreach ( $data as $i => $row ) {
$output[] = $chunk->process(
$row + [
'idx' => $i
],
$tpl
);
}
} else {
foreach ( $data as $i => $row ) {
$output[] = $modx->getChunk(
$tpl,
$row + [
'idx' => $i
]
);
}
}
return implode( $outputSeparator, $output );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment