Skip to content

Instantly share code, notes, and snippets.

@jenswittmann
Last active Aug 21, 2020
Embed
What would you like to do?
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