使用PHP中较小的JSON对象对大型JSON对象进行排序

使用PHP中较小的JSON对象对大型JSON对象进行排序

问题描述:

Before the cries of "DUPLICATE" begin, I've used several posts here and elsewhere as guides in trying to solve this problem and they've taken me a long way, but I'm stuck at the last step.

I have a JSON object that goes five deep. This object is used to populate a table on a webpage. Each item in the table has a score from 0-100, but they just get tossed into the table haphazardly. I want them to appear sorted with the lowest scores at the top.

What I did:

$jarr = json_decode($json, true);
$marr = $jarr['g'];

foreach ($marr as $key => $row){
    $score[$key] = $row['score'];
    $component[$key] = $row[$key];
}

array_multisort($score, SORT_ASC, $component, SORT_STRING, $marr);
print_r($marr);

Reasoning: the smaller object 'g' is an array of associative arrays inside the larger JSON object and is the only one that actually needs to be sorted, so I operated on only that portion and got functional code.

When I put this snippet into the source, it didn't break the page but I'm only getting the output of the scores; I need all the other information inside the lower arrays, also. I tried applying the logic to the larger JSON object, but that did nothing (could just be user error, here), and I tried sorting the smaller object and printing the larger one.

How can I return the whole JSON object with the 'g' object sorted?

Edit: I've found that part of the problem is that the source code isn't turning the JSON into an array where my code snippet is. That explains why they're not compatible, but still leaves me trying to get the sorting working.

That code does what I need it to. The last step was just to cast the resulting array as an object and make sure the Smarty code was referencing everything correctly.