我有两个数组(这是来自PHP的JSON数组)
一个
"result1": [
{
"driverId": "3",
"latitude": "23.752182",
"longitude": "90.377730",
"distance": "0.00011211999971692422",
"EstTime": 137
},
{
"driverId": "4",
"latitude": "23.75182",
"longitude": "90.3730",
"distance": "0.000171692422",
"EstTime": 111
}
]
两个
"result2": [
{
"driverId": "3"
}
]
我想比较这些数组。如果任何result1项driverID匹配result2的任何项,则从result1
跳过该项答案 0 :(得分:2)
您可以分两个阶段完成此任务。
首先收集driverId
以使用array_map
$exclude = array_map(
function($v) {
return $v['driverId'];
},
$json['result2']
);
然后使用array_filter
过滤掉您不想要的元素:
$result = array_filter(
$json['result1'],
function($a) use ($exclude) {
return !in_array($a['driverId'], $exclude);
}
);
我已使用以下代码对此进行了测试。如果您有单独的数组,只需在上面独立提供,而不是使用$json['result1']
。
$a = <<<JSON
{
"result1": [
{
"driverId": "3",
"latitude": "23.752182",
"longitude": "90.377730",
"distance": "0.00011211999971692422",
"EstTime": 137
},
{
"driverId": "4",
"latitude": "23.75182",
"longitude": "90.3730",
"distance": "0.000171692422",
"EstTime": 111
}
],
"result2": [
{
"driverId": "3"
}
]
}
JSON;
$json = json_decode($a, true);
答案 1 :(得分:2)
尝试以下方法。在这个答案中,我假设您已经应用json_decode()
并将$result1
和$result2
提取到PHP数组中。
继续上一次评论之后,编辑的代码将在5.2版中运行
<?php
// associative array of result1
$result1 = array(
array(
'driverId' => '3',
'latitude' => '23.752182',
'longitude' => '90.377730',
'distance' => '0.00011211999971692422',
'EstTime' => 137
),
array(
'driverId' => '4',
'latitude' => '23.75182',
'longitude' => '90.3730',
'distance' => '0.000171692422',
'EstTime' => 111
)
);
// associative array of result2
$result2 = array(
array(
'driverId' => '3'
)
);
// first, let's get a list of ids that we want to exclude
// run array map over the result2 and return the ids - this
// creates an array of "exclusion" ids. Note you could use
// foreach here also.
function pluckResultIds($result) {
return $result['driverId'];
}
$excludeIds = array_map('pluckResultIds', $result2);
var_dump($excludeIds); // result: array(3)
// next let's use array_filter to run over result1. for each
// entry in result1 - we check if the current driverId is in
// the exclusion array - if it is *not* we return the current
// this creates a new array $filtered containing only the
// filtered elements that do not match
$filtered = array();
foreach ($result1 as $result) {
$id = $result['driverId'];
if (!in_array($id, $excludeIds)) {
$filtered[] = $result;
}
};
var_dump($filtered);
收率:
array (size=1)
1 =>
array (size=5)
'driverId' => string '4' (length=1)
'latitude' => string '23.75182' (length=8)
'longitude' => string '90.3730' (length=7)
'distance' => string '0.000171692422' (length=14)
'EstTime' => int 111
希望这有帮助! :)