PHP中使用引用型foreach循环补全数组缺失的ProductIDRef值
Solution Using Reference Foreach + Lookup Map
Here's a clean, efficient way to achieve what you need using a reference-based foreach loop combined with a lookup array to track SKU-to-ProductIDRef mappings as we iterate:
// Your original array $array = [ ['id' => 1, 'SKU' => 'SKU_1', 'ProductIDRef' => '45645-12'], ['id' => 2, 'SKU' => 'SKU_2', 'ProductIDRef' => '43445-45'], ['id' => 3, 'SKU' => 'SKU_2', 'ProductIDRef' => ''], ]; // Initialize lookup array to store SKU -> ProductIDRef mappings $skuProductMap = []; // Loop with reference to modify original array directly foreach ($array as &$item) { // If current item has a non-empty ProductIDRef, update the lookup map if (!empty($item['ProductIDRef'])) { $skuProductMap[$item['SKU']] = $item['ProductIDRef']; } // If current item's ProductIDRef is empty and we have a mapping for its SKU, fill it elseif (isset($skuProductMap[$item['SKU']])) { $item['ProductIDRef'] = $skuProductMap[$item['SKU']]; } } // Unset the reference to prevent accidental modifications later unset($item); // Output the modified array to verify print_r($array);
How This Works:
- Reference Foreach: Using
&$itemmeans any changes we make to$itemdirectly alter the original array—no need to reassign values back to the array by index. - Lookup Map: The
$skuProductMaparray keeps track of the most recent non-emptyProductIDReffor each SKU. As we loop through the array:- We first update the map whenever we encounter a non-empty
ProductIDRef. - If we hit an item with an empty
ProductIDRefand its SKU exists in the map, we pull the stored value and assign it to the current item.
- We first update the map whenever we encounter a non-empty
Edge Cases to Consider:
- If multiple non-empty
ProductIDRefvalues exist for the same SKU later in the array, this code will update the map to use the latest one. If you want to preserve the first non-empty value instead, adjust the map update check to:if (!empty($item['ProductIDRef']) && !isset($skuProductMap[$item['SKU']])). - If an SKU has no prior non-empty
ProductIDRef, the empty value remains as-is (which is probably desired).
This approach is efficient (O(n) time complexity, since we only loop once) and doesn't require hardcoding indexes or tracking counters—perfect for automatically matching SKUs regardless of their position in the array.
内容的提问来源于stack exchange,提问作者bbruman
相关产品推荐
相关产品推荐

