如果k / v对位于可预测的位置,这可以通过array_slice解决, 不幸的是,它们在整个阵列中随机分散,我不得不这样做 创建我自己的愚蠢的小方法来重新分配事物。不幸的是,我在这里的while循环并没有解除深蹲....是否(当然有)更好的方法,或者纠正这种行为的方法?
重新分配和列入黑名单的循环。
$reports = array(
'inspection_number' =>"{$array['report_key']}",
'customer_number' =>"{$array['customer_number']}",
'customer_division' =>"{$array['customer_division']}",
'report_date' =>"{$array['report_date']}",
'customer' =>"{$array['customer']}",
'location' =>"{$array['location']}",
'region' =>"{$array['region']}",
);
while (list($k, $v) = each($reports)) {
if($array[$k]) { unset($array[$k], $array[$v]); }
}
数组,你可以看到$ array仍然有$ reports键。
array (
'shipper' => '',
'status' => '',
'po' => '',
'location' => '',
'inspector' => '',
'commodity' => '',
'count' => '',
'size' => '',
'label' => '',
'variety' => '',
'pack_date' => '',
'comments' => '',
'report_key' => '',
'region' => '',
'type' => 'melons',
'report_date' => '1969-12-31',
'customer_number' => '',
'customer' => '',
'customer_division' => '',
'staged' => 'true',
)array (
'`inspection_number`' => '\'\'',
'`customer_number`' => '\'\'',
'`customer_division`' => '\'\'',
'`report_date`' => '\'1969-12-31\'',
'`customer`' => '\'\'',
'`location`' => '\'\'',
'`region`' => '\'\'',
)
修改
如您所见,第二个数组STILL包含第一个数组中的键, 这些都没有被取消。即使我像这样进行多次递归循环
foreach($reports as $reportsKey => $reportsValue) {
foreach($array as $arrayKey => &$arrayValue) {
if($reportsKey == $arrayKey) { unset($arrayKey); }
} }
我正在尝试分配$reports
中的密钥,来自$array
的密钥/值,
然后从$array
取消设置复制的密钥。这可以用array_slice()
完成
如果$array
中的键位置是可预测的,但不幸的是它们
不是
奇怪的是,即使尝试分配$reports
中不存在的密钥也不起作用
$tmp = array();
foreach($array as $ak => $av) {
// if $reports['key_name'] does not exist, assign it to a new array.
if(!$reports[$ak]) { $tmp[$ak] = $av; }
}
答案 0 :(得分:0)
可能是因为你所讨论的数组的读取光标位于数组的末尾,你可以使用:
reset($reports);
在运行循环之前,虽然我建议使用:
foreach($reports as $k => $v) {
...
}
它更优雅。
答案 1 :(得分:0)
array_diff_assoc
向我提供了我需要的结果
$reports = array(
'inspection_number' =>"{$array['report_key']}",
'customer_number' =>"{$array['customer_number']}",
'customer_division' =>"{$array['customer_division']}",
'report_date' =>"{$array['report_date']}",
'customer' =>"{$array['customer']}",
'location' =>"{$array['location']}",
'region' =>"{$array['region']}",
);
$array = array_diff_assoc($array, $reports);
echo '<pre>'; var_export($array); var_export($reports); echo '</pre>'; break;
array (
'shipper' => '',
'status' => '',
'po' => '',
'inspector' => '',
'commodity' => '',
'count' => '',
'size' => '',
'label' => '',
'variety' => '',
'pack_date' => '',
'comments' => '',
'report_key' => '',
'type' => 'melons',
'staged' => 'true',
)
array (
'inspection_number' => '',
'customer_number' => '',
'customer_division' => '',
'report_date' => '1969-12-31',
'customer' => '',
'location' => '',
'region' => '',
)