【问题标题】:Invalid JSON format in using array_unique function [duplicate]使用 array_unique 函数时 JSON 格式无效 [重复]
【发布时间】:2019-12-31 08:34:30
【问题描述】:

我已经删除了以下数组的重复项:

$outcome['id'] = array_unique($outcome['id'], SORT_REGULAR);

但我得到了不受欢迎的 JSON 输出

    "id": {
        "0": {
            "id": 947,
            "label": "ABCD"
        },
        "1": {
            "id": 2175,
            "label": "EFGH"
        },
        "2": {
            "id": 15,
            "label": "IJKL"
        }
}

而不是下面的,这是理想的 JSON 输出:

"id": [
        {
            "id": 947,
            "label": "ABCD"
        },
        {
            "id": 2175,
            "label": "EFGH"
        },
        {
            "id": 15,
            "label": "IJKL"
        }
]

在 PHPStorm 上调试时,显示的结果是数组格式,但在 Postman 上,结果正在转换为对象!

【问题讨论】:

    标签: php arrays json array-unique


    【解决方案1】:

    array_unique 在删除项目时保留密钥。这意味着它将删除一些数组条目,但保持剩余项目的索引不变,从而导致不连续的数字索引(间隙)。数字索引中有间隙的数组或具有非数字索引的数组算作关联数组,在 JSON 中它成为 JSON 对象。您可以使用array_values 重置索引,例如

    $outcome['id']  = array_values(array_unique($outcome['id'], SORT_REGULAR));
    

    【讨论】:

    • 非常感谢!它奏效了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多