json_decode和json_encode问题 - 它为原始JSON添加了密钥

时间:2012-02-17 04:41:32

标签: php json

我有这个JSON字符串:

{
    "product": [
        {
            "id": "1",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "price": "30",
            "quantity": "100",
            "cartID": "1"
        },
        {
            "id": "1",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "price": "30",
            "quantity": "100",
            "cartID": "2"
        }
    ]
}

当我使用PHP函数 json_decode($ products,true),然后使用 json_encode($ products)重新编码它时,字符串变为:

{
    "product": {
        "1": {
            "id": "2",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "price": "30",
            "quantity": "100",
            "cartID": "2"
        },
        "2": {
            "id": "1",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "price": "30",
            "quantity": "100",
            "cartID": "3"
        }
    }
}

解码和重新编码后,它会为每个“产品”添加一个密钥

有解决方法吗?

2 个答案:

答案 0 :(得分:2)

在此发布此内容,因为它在评论中太难看了,但这是我在执行echo json_encode(json_decode('...your json...', true));后获得的PHP 5.3.6:

{"product":  [
     {"id":"1","title":"producta","size":"50","weight":"1000","price":"30","quantity":"100","cartID":"1"},
     {"id":"1","title":"producta","size":"50","weight":"1000","price":"30","quantity":"100","cartID":"2"}
]}

请注意缺少额外的钥匙。在重新编码之前,您是否正在对被修饰的数组进行任何操作?

答案 1 :(得分:0)

您可能正在使用mysqli_fetch_array而不是mysqli_fetch_assoc。意思是你是json解码一个关键的arreay而不是一个关联数组