jerome
jerome

Reputation: 715

PHP split array into 2 arrays by value

I'm having a hard time figuring out how to implement this so here it is. I have an array

$arr = array("purchase_order_details_id"=>array(
               0=>"POD1",
               1=>"POD1",
               2=>"POD2",
           ),
            "quantity_received"=>array(
               0=>5,
               1=>10,
               2=>20
            )
         );

I want to split the arrays into two. Into something like this.

$pod_2 = array("purchase_order_details_id"=>array(
       0=>"POD1",
       1=>"POD1"
       ),
       "quantity_received"=>array(
       0=>5,
       1=>10
       ));

$pod_1 = array("purchase_order_details_id"=>array(
       2=>"POD2"
       ),
       "quantity_received"=>array(
       2=>20
       ));

Anyone has an idea on how to do this ? Any thoughts is appreciated. Thanks

Upvotes: 1

Views: 195

Answers (3)

Jaydp
Jaydp

Reputation: 1039

Try with below code:

$array = array();   
foreach($arr['purchase_order_details_id'] as $key => $val)
{
    $array[$val]['purchase_order_details_id'][] = $val;
    $array[$val]['quantity_received'][] = $arr['quantity_received'][$key];
}

echo "<pre>";
    print_r($array);
echo "</pre>";

extract($array);

echo "<pre>";
    print_r($POD1);
echo "</pre>";

echo "<pre>";
    print_r($POD2);
echo "</pre>";

Upvotes: 3

Andreas
Andreas

Reputation: 23958

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);

https://3v4l.org/dBpuJ

Upvotes: 3

Vlam
Vlam

Reputation: 1798

foreach ($arr as $key => $val) {
    $size = ceil(count($val) / 2);

    $arr2 = array_chunk($val, $size, true);

    $pod_2[$key] = $arr2[0];
    $pod_1[$key] = $arr2[1];
}

var_dump($pod_2);
var_dump($pod_1);

Upvotes: 1

Related Questions