nineday900
nineday900
2019-08-13 19:17
采纳率: 72.7%
浏览 404
已采纳

二维数组根据相同值组成新数组?

旧数组:

$orders=array(
array(
"ordersn"=>'2019564842348',
"proName"=>'拖鞋',
"name"=>'张三',
"phone"=>"1800952442",
"proNum"=>2,
"proPrice"=>35.85
),
array(
"ordersn"=>'2019564842348',
"proName"=>'棉签',
"name"=>'张三',
"phone"=>"1800952442",
"proNum"=>1,
"proPrice"=>12
),
array(
"ordersn"=>'25451548412487',
"proName"=>'电脑',
"name"=>'李四',
"phone"=>"1564845487",
"proNum"=>1,
"proPrice"=>4600
),
);

如何通过相同的ordersn组装成新数组:

$orders=array(
    array(
            "ordersn"=>'2019564842348',
            "product"=>array(
                    array(
                            "proName"=>'拖鞋',
                            "proNum"=>2,
                            "proPrice"=>35.85
                        ),
                    array(
                            "proName"=>'棉签',
                            "proNum"=>1,
                            "proPrice"=>12
                        ),
                ),
            "name"=>'张三',
            "phone"=>'1800952442'
        ),
    array(
            "ordersn"=>'25451548412487',
            "product"=>array(
                    array(
                            "proName"=>'电脑',
                            "proNum"=>1,
                            "proPrice"=>4600
                        ),
                ),
            "name"=>'李四',
            "phpone"=>"1564845487",
        ),
    );
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • weixin_43867346
    weixin_43867346 2019-08-14 11:30
    已采纳
    $orders=array(
    array(
    "ordersn"=>'2019564842348',
    "proName"=>'拖鞋',
    "name"=>'张三',
    "phone"=>"1800952442",
    "proNum"=>2,
    "proPrice"=>35.85
    ),
    array(
    "ordersn"=>'2019564842348',
    "proName"=>'棉签',
    "name"=>'张三',
    "phone"=>"1800952442",
    "proNum"=>1,
    "proPrice"=>12
    ),
    array(
    "ordersn"=>'25451548412487',
    "proName"=>'电脑',
    "name"=>'李四',
    "phone"=>"1564845487",
    "proNum"=>1,
    "proPrice"=>4600
    ),
    );
    $returnData = [];
    foreach($orders as $k => $v){
    if(isset($returnData[$v['ordersn']])){
            $returnData[$v['ordersn']]['product'][] = [
                    'proName'  => $v['proName'],
                    'proNum'   => $v['proNum'],
                    'proPrice' => $v['proPrice'] 
            ];
        }else{
            $returnData[$v['ordersn']] = [
                'ordersn' => $v['ordersn'],
                'product' => [[
                    'proName'  => $v['proName'],
                    'proNum'   => $v['proNum'],
                    'proPrice' => $v['proPrice'] 
                ]],
                'name'  => $v['name'],
                'phone' => $v['phone']
            ];
        }
    }
    print_r(array_values($returnData));die;
    
    点赞 评论

相关推荐