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

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看