doulie0178 2017-08-16 17:45
浏览 63
已采纳

使用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.

  • 写回答

1条回答 默认 最新

  • drm30963 2017-08-17 18:04
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀