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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化