【问题标题】:Sorting a table similar to JSON对类似于 JSON 的表进行排序
【发布时间】:2017-07-18 09:25:32
【问题描述】:

我想知道如何按字母顺序对数组进行排序

[
  {"people":"Julien SMITH","uid":"598"},
  {"people":"John SMITH","uid":"7232"}
]

我试过了

array_multisort($myArray['people'],SORT_ASC,$myArray['uid'])

但它当然行不通,因为 people 和 uid 并不是表格的真正列...

我找不到与我的情况类似的东西..

感谢您的帮助

【问题讨论】:

    标签: php arrays json sorting


    【解决方案1】:

    使用usort() 函数。它会做你想做的事。

    $jsonObj = '[
     {"people":"Julien SMITH","uid":"598"},  
    {"people":"Don SMITH","uid":"7232"},
    {"people":"Allan SMITH","uid":"3232"}
    ]';
    
    $arrObj = json_decode($jsonObj,true);
    
    function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
    }
    
    usort($arrObj, build_sorter('people'));
    
    foreach ($arrObj as $item) {
    echo $item['people'] . ', ' . $item['uid'] . "n";
    }   
    

    【讨论】:

      【解决方案2】:

      首先您需要将您的 json 对象转换为数组。然后你可以应用排序

      $json_obj = '[
        {"people":"Julien SMITH","uid":"598"},  
        {"people":"John SMITH","uid":"7232"}
      ]';
      $myArray = json_decode($json_obj,true);
      
      array_multisort($myArray,SORT_ASC);
      echo json_encode($myArray); // op: [{"people":"John SMITH","uid":"7232"},{"people":"Julien SMITH","uid":"598"}]
      

      【讨论】:

      • 它并没有真正起作用,因为我需要返回一个像 JSON 这样的数组,如果我按照你说的做,那么我返回 json_encode($myArray),它不起作用...
      猜你喜欢
      • 2016-10-26
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多