dpwgzi7987
2018-06-07 03:27
浏览 152
已采纳

PHP按数值将数组拆分为2个数组

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douyue5856 2018-06-07 03:53
    已采纳

    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

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题