如何对关联数组进行排序-从JSON文件解码-在PHP中按字母顺序排列

问题描述 投票:-1回答:1

我有以下JSON文件:

[
    {
        "ID_id": "Hbx6gpb7rx",
        "DT_createdAt": "2020-01-29T04:39:01",
        "DT_updatedAt": "2020-02-07T15:20:49",
        "ST_text": "AA"
    },
    {
        "ID_id": "gH51tKUZUr",
        "DT_createdAt": "2020-02-01T09:18:19",
        "DT_updatedAt": "2020-02-05T09:11:37",
        "ST_text": "HH"
    },
    {
        "ID_id": "TVzGdgVKJE",
        "DT_createdAt": "2020-03-06T07:27:35",
        "DT_updatedAt": "2020-02-08T15:34:07",
        "ST_text": "ZZ"
    },
    {
        "ID_id": "jrQUzELDpb",
        "DT_createdAt": "2020-04-10T12:13:41",
        "DT_updatedAt": "2020-02-10T12:30:47",
        "ST_text": "EE"
    }
]

我想做的是通过"ST_text"键按升序和降序对它的关联数组进行排序。

这是我的PHP代码(从AJAX函数调用:):

    <?php 
    $tableName = $_POST['tableName']; 
    $key = $_POST['key']; // <-- this is 'ST_text'
    $orderBy = $_POST['orderBy']; // <-- this is either 'descending' or 'ascending'

    // Get JSON data
    $data = file_get_contents($tableName. '.json');
    $data_array = json_decode($data, true);

    if (isset($key)) {
       if ($orderBy != ""){
                // Ascending
                if ($orderBy == "ascending") {
                    usort($data_array, function ($item1, $item2) {
                        return $item1[$key] <=> $item2[$key];
                    });
                // Descending
                } else if ($orderBy == "descending") {
                    usort($data_array, function ($item1, $item2) {
                        return $item2[$key] <=> $item1[$key];
                    });
                }
            // Descending (default)
            } else {
               usort($data_array, function ($item1, $item2) {
                  return $item2[$key] <=> $item1[$key];
               });
            }

        }// ./ If

    echo json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>

不幸的是,它不起作用,它总是给我以下输出:

AA 
ZZ 
EE 
HH

我将$orderBy变量设置为'ascending'或'descending'都没关系。

我的PHP代码在做什么错?

php arrays json sorting associative-array
1个回答
1
投票

$ key变量在函数范围内不可用。若要更正,可以对每个usort调用使用以下示例:

      usort($data_array, function  ($item1, $item2) use ($key)  {

            return $item1[$key] <=> $item2[$key];
        });

当设置为降序时,我现在看到:

[
{
    "ID_id": "TVzGdgVKJE",
    "DT_createdAt": "2020-03-06T07:27:35",
    "DT_updatedAt": "2020-02-08T15:34:07",
    "ST_text": "ZZ"
},
{
    "ID_id": "gH51tKUZUr",
    "DT_createdAt": "2020-02-01T09:18:19",
    "DT_updatedAt": "2020-02-05T09:11:37",
    "ST_text": "HH"
},
{
    "ID_id": "jrQUzELDpb",
    "DT_createdAt": "2020-04-10T12:13:41",
    "DT_updatedAt": "2020-02-10T12:30:47",
    "ST_text": "EE"
},
{
    "ID_id": "Hbx6gpb7rx",
    "DT_createdAt": "2020-01-29T04:39:01",
    "DT_updatedAt": "2020-02-07T15:20:49",
    "ST_text": "AA"
}

]

© www.soinside.com 2019 - 2024. All rights reserved.