dongsheng1698 2018-11-05 04:22
浏览 137
已采纳

在PHP中组合两个数组匹配键

I need to Combine two array in PHP,and also have to match the keys

Here`s my array

array1 look like

[
    0 => "num",
    1 => "No",
    2 => "Name",
    3 => "Phone",
    4 => "Price",
    5 => "Date"
]

array2 look like

[
    0 =>[
        "No" => "FR201605832",
        "Price" => 199.0,
        "Date" => "2016-09-01",
        "num" => "19",
        "Name" => "Tom",
        "Phone" => "0900123456"
    ],
    1 =>[
        "No" => "EC2016010100001",
        "Price" => 1680.0,
        "Date" => "2016-09-01",
        "num" => "1680",
        "Name" => "Ted",
        "Phone" => "0900321654"
    ]
]

And Here`s Result What I want

[
    0 =>[
        "num" => "19",
        "No" => "FR201605832",
        "Name" => "Tom",
        "Phone" => "0900123456",
        "Price" => 199.0,
        "Date" => "2016-09-01",
    ],
    1 => [
        "num" => "1680",
        "No" => "EC2016010100001",
        "Name" => "Ted",
        "Phone" => "0900321654",
        "Price" => 1680.0,
        "Date" => "2016-09-01",
    ]
]

array1 is User reOrder the input excel heading,I can get the reorder request but don`t know how to combine with the value

Plz help me to combine two array and export the expect result,Thx


Here is the next step

Renam the Result array key by array3

array3 look like

array:6 [▼

"num" => "id"

"No" => "ECNo"

"Name" => "User"

"Phone" => "Mobile"

"Price" => "Total"

"Date" => "PayDay"

]

I tried

foreach($exportdata as &$val){

$val[$values] = $val[$keys];

unset($val[$value]);

}

But get error Illegal offset type

any good idea?

  • 写回答

2条回答 默认 最新

  • duanlv1366 2018-11-05 04:44
    关注

    Use array_flip() and array_merge() to achieve your result

    $new = [];
    foreach ($array as $value) {
      $new[] = array_merge(array_flip($order),$value);
    }
    dd($new);
    

    you can order your second array when you create that array. without go for another foreach so your second array data something different i guess so try this way

    $new = [];
    foreach ($array as $value) {
       if(isset($value['num'])) $data['num'] = $value['num'];
       if(isset($value['No'])) $data['No'] = $value['No'];
       if(isset($value['Name'])) $data['Name'] = $value['Name'];
       if(isset($value['Phone'])) $data['Phone'] = $value['Phone'];
       if(isset($value['Price'])) $data['Price'] = $value['Price'];
       if(isset($value['Date'])) $data['Date'] = $value['Date'];
    
       $new[] = $data;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?