I'm having a hard time figuring out how to implement a script to group value-related subarray column values.
$arr = [
"purchase_order_details_id" => ["POD1", "POD1", "POD2"],
"quantity_received" => [5, 10, 20],
];
I want to split and group the data according to purchase_order_details_id value and retain the data relationships with quantity_received.
Desired result:
$pod_2 = [
"purchase_order_details_id" => ["POD1", "POD1"],
"quantity_received" => [5, 10],
];
$pod_1 = [
"purchase_order_details_id" => [2 => "POD2"],
"quantity_received" => [2 => 20]
];
I use array_intersect to find the POs in a loop of unique POs.
Then I use array_inyersect_key to get the quantity.
This requires only one iteration per unique Purchase_order_detali_id.
Meaning it has a much better performance than looping the full array.
Edit: added extract to create the two variables. But I would rather keep them in the array if I was you.
$pods = array_unique($arr["purchase_order_details_id"]);
Foreach($pods as $pod){
$PO = array_intersect($arr["purchase_order_details_id"], [$pod]);
$qt = array_intersect_key($arr["quantity_received"], $PO);
$new[$pod] = ["purchase_order_details_id" => $PO, "quantity_received" => $qt];
}
Var_dump($new);
extract($new);