2016-12-19 27 views
0

數組鑑於訂單中佔各行項目的項目的數組的最佳方式:什麼是X總的項目添加到每個項目,而排序在PHP

var_export([[ 
     'order_id' => 1, 
     'driver_id' => 100, 
     'product_id' => 2 
     ], 
     [ 
     'order_id' => 1, 
     'driver_id' => 100, 
     'product_id' => 1 
     ], 
     [ 
     'order_id' => 2, 
     'driver_id' => 50, 
     'product_id' => 1 
     ] 
]); 

有由driver_id進行排序,然後是product_id。是否有可能在排序過程中的附加字段添加到每個項目,以便在年底我有類似:

var_export([[ 
     'order_id' => 2, 
     'driver_id' => 50, 
     'product_id' => 1, 
     'sequence' => '1 of 1' 
     ], 
     [ 
     'order_id' => 1, 
     'driver_id' => 100, 
     'product_id' => 1, 
     'sequence' => '1 of 2' //if easier, this could be 2 of 2 and the one below 1 of 2 as long as they are ordered this way in the array 
     ], 
     [ 
     'order_id' => 1, 
     'driver_id' => 100, 
     'product_id' => 2, 
     'sequence' => '2 of 2' 
     ] 
]); 

sequence顯示訂單中的項目的迭代次數(ORDER_ID 1在兩個項目所以每個應該有一個序列x爲2,但是在訂單內哪個項目標記爲1,哪個項目標記爲2)並不重要。

如果排序時無法做到這一點,那麼添加此字段的最佳方法是什麼?

+0

未來,請使用'var_export'來顯示源數據。這樣它可以複製粘貼。 – sevavietl

+0

@sevavietl我已更新使用var_export並更改了數據以更清晰地顯示排序順序。 –

回答

0

你可以嘗試這樣的事情:

// Get array of all order ids. 
$orderIds = array_column($array, 'order_id'); 
// Sort $array by order ids. 
array_multisort(
    array_column($array, 'driver_id'), 
    array_column($array, 'product_id'), 
    $orderIds, 
    $array 
); 
// Count order ids occurances. 
$orderIdsCounts = array_count_values($orderIds); 

$counter = 0; 
$array = array_map(function ($orderId, $item) use (&$counter, $orderIdsCounts) { 
    $counter += 1; 

    $item['sequence'] = "$counter of {$orderIdsCounts[$orderId]}"; 

    // Reset the counter if order id total is reached. 
    $counter = $counter === $orderIdsCounts[$orderId] ? 0 : $counter; 

    return $item; 
}, $orderIds, $array); 

這裏是working demo

+0

獲取並添加序列字段但不重新排序原始數組。我在問是否可以同時進行這兩項操作。用'driver_id'命令原始數組,然後'product_id'。那麼這個map函數可以被混合到一個'usort'中,還是需要做兩個單獨的迭代來達到我想要的結果呢? –

+0

@RobinSouthgate,也許你可以一次做所有事情,但這確實使邏輯複雜化了。所以我會傳遞兩個更多的參數給'array_multisort'。查看更新後的答案。 – sevavietl

相關問題