Last active
August 21, 2020 14:54
-
-
Save jenswittmann/d936aed4d756b0d6baf9523bf270fcf6 to your computer and use it in GitHub Desktop.
loopJSON (MODX Snippet)
This file contains 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 | |
/** | |
* 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