顶层的产品数组是$csv. 在下面的摘录中,数字 [584],[585] 代表下一个数组级别$product=>$data_col如下所示: [584] => Array ( [No_] => II14511 [Manufacturer ID] => CLT-M504S [Description] => SAM CON CLT-M504S [LQ Price] => 120.00000000000000000000 [Retail Price Incl_ GST] => 171.60000000000000000000 [AvailableQty] => 0.00000000000000000000 [Rocklea] => 0.00000000000000000000 [Sydney] => [Net Weight] => 0.50000000000000000000 [Item Category Code] => SAM [Product Group Code] => CON [Minor Category 1] => TONER [Minor Category 2] => # [Vendor Name] => Samsung [Vendor URL] => www.samsung.com.au [Item URL] => [Warranty] => [Dimension] => [EAN Barcode] => 8806085031999 [Description1] => Samsung CLT-M504S, SEE toner for CLP-415/ CLX-4195 Series LBP & MFP - Magenta Toner 1800 pages<br /> [Image] => https://auscompcomputers.com/uploads/image/SAM-CON-CLT-M504S.jpg ) [585] => Array ( [No_] => II14772 [Manufacturer ID] => DK-22205 [Description] => BRO CON LABELROLL-DK-22205 [LQ Price] => 25.00000000000000000000 [Retail Price Incl_ GST] => 35.75000000000000000000 [AvailableQty] => 0.00000000000000000000 [Rocklea] => 0.00000000000000000000 [Sydney] => 0.00000000000000000000 [Net Weight] => 0.50000000000000000000 [Item Category Code] => BRO [Product Group Code] => CON [Minor Category 1] => CON-LABEL-ROLL [Minor Category 2] => # [Vendor Name] => Brother )因此,我有一个具有结构的数组$csv as $product as $data_col => $value但是,我想$data_col参考通缉列表选择性地删除一些数组$data_col,我将其称为$wanted_data_cols.它似乎不会导致整个阵列发生变化。您能否建议如何进行这项工作,或者如果您觉得您有一个可以实现相同目标的卓越解决方案,我会接受。
1 回答
牛魔王的故事
TA贡献1830条经验 获得超3个赞
您现有代码的问题在于,当您尝试使用unset()该值时,您使用的是实际值而不是索引来删除该项目 - 这是行不通的。
要修复原始代码 -
foreach ($csv as $key => $product){
foreach ($product as $column => $data_col){
if(!in_array($column,$wanted_data_cols)){
unset($csv[$key][$column]);
}
}
}
另一种方法是使用array_intersect_key(),这允许您只保留第二个数组中的键。但要做到这一点 - 您需要array_flip()在要保留的字段上使用,以便字段名称最终成为键......
$wanted_data_cols = array_flip($wanted_data_cols);
foreach ($csv as $key => $product){
$csv[$key] = array_intersect_key($product, $wanted_data_cols);
}
最后一个建议是,如果可能的话,这应该在加载数据时完成,这样可以节省在内存中保存无用数据并消除进行第二次循环的需要。
- 1 回答
- 0 关注
- 138 浏览
添加回答
举报
0/150
提交
取消