PHP数组:如何过滤参数

时间:2016-03-28 09:54:18

标签: php arrays json

我有一个带有+/- 300项的巨大JSON字符串。一个缩短的例子:

[
{"DateGps":"2016-03-25T19:28:19+01:00","DateReceived":"2016-03-25T19:28:20.163+01:00","Longitude":5.85294,"Latitude":51.84475,"Speed":55,"VehicleNumber":"678","TravelNumber":"4321"},
{"DateGps":"2016-03-25T19:28:13+01:00","DateReceived":"2016-03-25T19:28:14.065+01:00","Longitude":4.8139,"Latitude":52.43844,"Speed":23,"VehicleNumber":"2335","TravelNumber":"1234"}
]

$array = json_decode($json,true); // i will convert this into a array. 

但是我怎样才能得到VehicleNumber与VehicleNumber 2335相同的行?

2 个答案:

答案 0 :(得分:2)

您可以像{/ p>一样使用array_filter

$array = json_decode($json,true);
$resulted_array = array_filter($array,function($v){ return ($v['VehicleNumber'] == 2335);});
print_r($resulted_array);

答案 1 :(得分:0)

Uchiha's answer几乎相同,但使用anonymous class作为FilterIterator
在这种情况下,它只增加(不必要的)复杂性(特别是因为json_decode(,true)返回一个数组,因此无论如何整个数据都在内存中)。但是如果你有大量的数据,你可以一步一步地接收它,迭代器和/或generators可能会派上用场; - )

<?php
$data = json_decode(data(), true);
$it = new class(new ArrayIterator($data)) extends FilterIterator {
    public function accept() { return '2335'==$this->current()['VehicleNumber']; }
};

foreach($it as $v) {
    var_export($v);
}

function data() {
    return <<< eoj
[
{"DateGps":"2016-03-25T19:28:19+01:00","DateReceived":"2016-03-25T19:28:20.163+01:00","Longitude":5.85294,"Latitude":51.84475,"Speed":55,"VehicleNumber":"678","TravelNumber":"4321"},
{"DateGps":"2016-03-25T19:28:13+01:00","DateReceived":"2016-03-25T19:28:14.065+01:00","Longitude":4.8139,"Latitude":52.43844,"Speed":23,"VehicleNumber":"2335","TravelNumber":"1234"}
]
eoj;
}