PHP:搜索并删除JSON对象

时间:2017-06-02 06:54:10

标签: php json

我有一个非常嵌套的JSON文件。如何删除包含我的值的数组?例如:我想从JSON文件中删除{"customer":"Customer1","date":"2017-06-03"...},我已经知道“Customer1”

{
            "info": [{
                "customer": "Customer1",
                "date": "2017-06-03",
                "beacons": [{
                    "data1": "1234",
                    "data2": "Test1",
                }, {
                    "data1": "0088",
                    "data2": "Test2",
                }]
            },{
                "customer": "Customer2",
                "date": "2017-06-03",
                "beacons": [{
                    "data1": "dcdd4",
                    "data2": "Test3",
                }, {
                    "data1": "0088",
                    "data2": "Test4",
                }]
            }]
        }

谢谢!

3 个答案:

答案 0 :(得分:1)

您的json数据存在一些问题。这不是有效的json数据;我解码了josn数据&然后检查"客户" value =' Customer1',然后从主数组中删除数组。

应该是这样的:

$jsonData = '{"info ": [{
    "customer ": "customer1 ",
    "date ": "2017 - 06 - 03 ",
    "beacons ": [{
        "data1 ": "1234",
        "data2 ": "Test1"
    }]
}, {
    "customer": "customer2 ",
    "date": "2017 - 06 - 04 ",
    "beacons": [{
        "data1": "dcdd4",
        "data2": "Test3"
    }]
 }]
}';

$myData = json_decode($jsonData,true);


foreach($myData["info"] as $k=>$arr) {
    if($arr["customer"] == "customer1") {
       unset($myData["info"][$k]);
    }
}    

答案 1 :(得分:0)

使对象分配给一个obj示例:=>

var myobj={"info": [{ ...... }]}  

。这个下面的函数将用于搜索对象数组中的确切值 使用如下所示的参数调用该函数

searchObj (myobj, Customer1);

function searchObj (obj_name, searchingval) {
    for (var key in obj_name) {
        var value = obj_name[key];

        if (typeof value === 'object') {
            searchObj(value, searchingval);
        }

        if (value === searchingval) {
            console.log('property name=' + key + '    property value=' + value);
        }

    }
}

答案 2 :(得分:0)

上一个答案中的一个小修正。

请拨打这样的功能。搜索值应该是astring格式的值。

searchObj (myobj, 'Customer1');