Skip to content
Advertisement

PHP Sort results from key values inside multiple json files

is it possible to sort the results by key value inside separate json files? I need to sort the result by “id” value. Sorry if this is a duplicate but I’ve searched entire internet and couldn’t find a solution.

Many thanks for your help.

<div class="container grid grid-cols-2 gap-6 tablet:grid-cols-3 desktop:grid-cols-6">
    <?php
    $i = 0;
    $dir = (new DirectoryIterator(__DATA_PAGES_PATH__ . 'products/content/' . $lang));
    foreach ($dir as $productsdata) {
        if ($productsdata->isDot()) continue;
        $productdata = json_decode(file_get_contents(__DATA_PAGES_PATH__ . 'products/content/' . $lang . "/" . $productsdata));
        if ($productdata->popular > 0) {
    ?>
            <?php echo $productdata->id ?>
    <?php
        };
        if (++$i == 6) break;
    }
    ?>
</div>

Content of multiple json files inside the directory:

{
    "id": 0,
    "name": "prd-name-0",
    "category": "prd-category-0"
}
{
    "id": 1,
    "name": "prd-name-1",
    "category": "prd-category-1"
}

Advertisement

Answer

So this was my solution for anyone who might need this. thanks to @CBroe

function sortkey($folder, $key)
{
    $GLOBALS['files'] = glob(__data__ . $folder . '/' . $GLOBALS['lang'] . '/*.json');
    $GLOBALS['sort'] = [];
    foreach ($GLOBALS['files'] as $GLOBALS['file']) {
        $GLOBALS['thisData'] = file_get_contents($GLOBALS['file']);
        $GLOBALS['thisDataArr'] = json_decode($GLOBALS['thisData']);
        if (isset($GLOBALS['thisDataArr']->$key)) {
            $GLOBALS['sort'][$GLOBALS['thisDataArr']->$key] = basename(str_replace('.json', '', $GLOBALS['file']));
        }
    }
    ksort($GLOBALS['sort']);
    // var_dump($GLOBALS['sort']);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement