遍历多维数组:添加值到新数组并差异化处理匹配元素
Alright, let's break down how to solve this problem. Based on your sample array (which looks like a PHP nested array), we'll walk through iterating through the structure, extracting elements to a new array, and applying special logic to items that match specific values.
First, let's formalize your sample array into valid PHP code for clarity:
$originalArray = [ [ [ 'productCode' => 'HQ768H', 'startTimeLocal' => '2018-04-17 14:00:00', 'endTimeLocal' => '2018-04-17 16:00:00', 'totalQuantity' => 2, 'amount' => 170, 'extras' => [], 'transferReturn' => '', 'subtotal' => 170 ], [ 'productCode' => 'PLJ6HP', 'startTimeLocal' => '2018-04-15 14:00:00', 'endTimeLocal' => '2018-04-15 16:00:00', 'totalQuantity' => 2, 'amount' => 170, 'extras' => [], 'transferReturn' => '', 'subtotal' => 170 ] ] ];
Solution 1: Nested Loops (For Fixed Depth Arrays)
If you know your array has a fixed 3-level structure, nested foreach loops are straightforward and efficient. Let's say we want to:
- Extract
productCode,startTimeLocal, andamountinto a new array - Double the
amountand add a special flag for items whereproductCodeequalsHQ768H
Here's the code:
$newArray = []; // Iterate through the outer array foreach ($originalArray as $level1) { // Iterate through the middle-level array of orders foreach ($level1 as $order) { // Base extraction of required fields $processedOrder = [ 'product_code' => $order['productCode'], 'start_time' => $order['startTimeLocal'], 'amount' => $order['amount'] ]; // Differentiated processing for matching values if ($order['productCode'] === 'HQ768H') { $processedOrder['amount'] *= 2; // Double the amount $processedOrder['is_special'] = true; // Add a special marker } else { $processedOrder['is_special'] = false; } // Add the processed item to our new array $newArray[] = $processedOrder; } } // Output the result print_r($newArray);
Running this will give you:
Array ( [0] => Array ( [product_code] => HQ768H [start_time] => 2018-04-17 14:00:00 [amount] => 340 [is_special] => 1 ) [1] => Array ( [product_code] => PLJ6HP [start_time] => 2018-04-15 14:00:00 [amount] => 170 [is_special] => ) )
Solution 2: Recursive Function (For Variable Depth Arrays)
If your array might have unpredictable nesting levels, a recursive function is better—it will automatically traverse every level until it finds the order items we care about.
function processNestedOrders($array, &$resultArray) { foreach ($array as $item) { // Check if the current item is an order (has productCode field) if (isset($item['productCode'])) { $processed = [ 'product_code' => $item['productCode'], 'start_time' => $item['startTimeLocal'], 'amount' => $item['amount'] ]; // Apply your special logic here if ($item['productCode'] === 'HQ768H') { $processed['amount'] *= 2; $processed['is_special'] = true; } $resultArray[] = $processed; } // If it's another nested array, recurse into it elseif (is_array($item)) { processNestedOrders($item, $resultArray); } } } $newArray = []; processNestedOrders($originalArray, $newArray); print_r($newArray);
Customizing the Differentiated Logic
You can adjust the matching condition to fit your needs—for example:
- Match against
totalQuantityinstead ofproductCode - Modify
subtotalinstead ofamount - Add multiple conditions (e.g.,
if ($order['productCode'] === 'HQ768H' && $order['totalQuantity'] > 1))
Just update the if block in the code above to match your specific requirements.
内容的提问来源于stack exchange,提问作者Jason Whalan

