php 合并多維陣列問題

來源:互聯網
上載者:User
有2個數組

$array1 =[[0]=>  array(3) {    ["id"]=> "1",    ["uid"]=>'123',    ["status"]=>'0'[1]=>  array(3) {    ["id"]=> "2",    ["uid"]=>'321',    ["status"]=>'1']$array2 =[[0]=>  array(2) {    ["uid"]=> "123",    ["name"]=>'張三'[1]=>  array(2) {    ["uid"]=> "321",    ["name"]=>'李四']

我在迴圈輸出array1的時候。如何把uid替換成array2中的name?

foreach($array1 as $item) {  $item['status']= $item['status']==1?'是':'否';  $item['uid']= xxx;//這裡如何替換成name?  $newarr[] = $item;}

回複內容:

有2個數組

$array1 =[[0]=>  array(3) {    ["id"]=> "1",    ["uid"]=>'123',    ["status"]=>'0'[1]=>  array(3) {    ["id"]=> "2",    ["uid"]=>'321',    ["status"]=>'1']$array2 =[[0]=>  array(2) {    ["uid"]=> "123",    ["name"]=>'張三'[1]=>  array(2) {    ["uid"]=> "321",    ["name"]=>'李四']

我在迴圈輸出array1的時候。如何把uid替換成array2中的name?

foreach($array1 as $item) {  $item['status']= $item['status']==1?'是':'否';  $item['uid']= xxx;//這裡如何替換成name?  $newarr[] = $item;}

2個數組的匹配資料的位置是一一對應的麼? 如果這樣, 比較簡單:

$count = count($array1);for ($i = 0; $i < $count; ++$i) {    $array1[$i]['uid'] = $array2[$i]['name'];}

這樣就可以了, 這種情況用foreach反而不方便.

假如資料不匹配, 需要在array2中搜尋的話, 給個簡單的例子:

foreach ($array1 as &$item) {    $item['uid'] = get_name($array2, $item['uid']);}function get_name(&$data, $uid){    foreach ($data as &$item) {        if ($item['uid'] == $uid) {            $name = $item['name']            unset($item);            return $name;        }    }}

再來拓展一下

$array3 = function() use($array2) {    $res = array();    foreach ($array2 as $item) {        $res[$item['uid']] = $item['name'];    }    return $res;};foreach ($array1 as &$item) {    $item['uid'] = $array3[$item['uid']];}

$array2 = array_column($array2, 'name', 'uid');foreach($array1 as &$arr) $arr['uid'] = $array2[$arr['uid']];

噴了,換個思路?
http://php.net/manual/en/function.array-merge-recursive.php

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.