使用 PHP 按另一个数组中的值过滤数组
Posted
技术标签:
【中文标题】使用 PHP 按另一个数组中的值过滤数组【英文标题】:Filter array by values in another array with PHP 【发布时间】:2017-01-24 11:57:44 【问题描述】:我有一个这样的数组:
[
"Firepack_sn":"20012205",
"Installation_Date":"",
"Type":"EH","Standard":"VAS",
"Capacity_m3h":"81",
"Pressure_bar":"3,4",
"Rpm":"2930",
"Power_kw":"72"
,
"Firepack_sn":"20023901",
"Installation_Date":"",
"Type":"DH","Standard":"VAS",
"Capacity_m3h":"195",
"Pressure_bar":"4,2",
"Rpm":"2000",
"Power_kw":"72"
]
还有一个这样的数组2:
[
"user_id":"40009",
"firepack_id":"20012205",
"activated":"1"
,
"user_id":"40009",
"firepack_id":"21020393",
"activated":"0"
]
现在我想过滤第一个数组,所以我只获取array2中存在的Firepack_sn元素作为firepack_id
所以我希望输出是这样的:
[
"Firepack_sn":"20012205",
"Installation_Date":"",
"Type":"EH","Standard":"VAS",
"Capacity_m3h":"81",
"Pressure_bar":"3,4",
"Rpm":"2930",
"Power_kw":"72"
]
我怎样才能做到这一点?
【问题讨论】:
【参考方案1】:这是一种方法:
首先,您需要提取您需要查找的firepack_id,然后您需要循环通过$arr1并检查Firepack_sn是否与您之前提取的firepack_id相同,如果是,则将其添加到一个数组。
$arr1 = json_decode('["Firepack_sn":"20012205","Installation_Date":"","Type":"EH","Standard":"VAS","Capacity_m3h":"81","Pressure_bar":"3,4","Rpm":"2930","Power_kw":"72","Pump_Type":"KSB KFP50-200","Motor_Type":"DOOSAN PU066 VAS/CEA","Controller_Type":"WB882-E10 VAS","Pump_sn":"085259","Motor_sn":"EARPA209635","Controller_sn":"","Servicelevel":"","Cust_id":"0","Cust_branche":"","Cust_name":"","Cust_address1":"","Cust_zipcode":"","Cust_city":"","Cust_country":"","Cust_Phone":"","Cust_coachlevel":"","Site_Name":"E-set","Site_address1":"","Site_address2":"","Site_address3":"","Site_zipcode":"","Site_city":"","Site_country":"","Site_contact":"","Site_phone":"","activated":"1","Firepack_sn":"20023901","Installation_Date":"","Type":"DH","Standard":"VAS","Capacity_m3h":"195","Pressure_bar":"4,2","Rpm":"2000","Power_kw":"72","Pump_Type":"KSB KFP50-200","Motor_Type":"DOOSAN PU066 VAS/CEA","Controller_Type":"WB882-E10 VAS","Pump_sn":"085259","Motor_sn":"EARPA209635","Controller_sn":"","Servicelevel":"","Cust_id":"0","Cust_branche":"","Cust_name":"","Cust_address1":"","Cust_zipcode":"","Cust_city":"","Cust_country":"","Cust_Phone":"","Cust_coachlevel":"","Site_Name":"D-set","Site_address1":"","Site_address2":"","Site_address3":"","Site_zipcode":"","Site_city":"","Site_country":"","Site_contact":"","Site_phone":"","activated":"0"]');
$arr2 = json_decode('["user_id":"40009","firepack_id":"20012205","activated":"1","user_id":"40009","firepack_id":"21020393","activated":"0"]');
$firepackIds = array();
foreach($arr2 as $item)
$firepackIds[] = $item->firepack_id;
$goodRows = array();
foreach($arr1 as $item)
if(in_array($item->Firepack_sn, $firepackIds))
$goodRows[] = $item;
echo json_encode($goodRows);
希望这会有所帮助。
【讨论】:
谢谢!你的答案没有用,但做了一些小的编辑它就奏效了。编辑:$item->firepack_id; = $item['firepack_id'] $item->Firepack_sn = $item['Firepack_sn'] @DNC 什么不起作用。我在理解您的编辑时遇到了一些困难,我怀疑其中的某些部分已被删除,您能否在某个地方发布一个要点以便我可以更新我发布的内容?以上是关于使用 PHP 按另一个数组中的值过滤数组的主要内容,如果未能解决你的问题,请参考以下文章