douyan4470 2012-06-27 22:28
浏览 14
已采纳

是否有一个函数在PHP中组合这些数组?

Given arrays 'a1' and 'b1' how may they be combined them to produce the final array? Basically replacing the value within 'a1' with the array data for the matching value within 'b1'. I guess the question would be if there is a function that can do this that I'm not seeing.

$a1 = array('id1'=>array('a'=>'444-444',
                         'b'=>'222-222',
                         'c'=>'111-111'),
            'id2'=>array('a'=>'888-888',
                         'b'=>'666-666',
                         'c'=>'555-555')
           );

$b1 = array('222-222'=>array('first'=>array('9999',
                                            'dddd',
                                            'yyyy'),
                             'second'=>'mmgghh'
                            ),
            '666-666'=>array('first'=>array('bbbb',
                                            'cccc',
                                            '7777'),
                             'second'=>'ffffgggg'
                            )
           );

Desired combination:

array(2) {
  ["id1"]=>
  array(3) {
    ["a"]=>
    string(7) "444-444"
    ["b"]=>
    array(1) {
      ["222-222"]=>
      array(2) {
        ["first"]=>
        array(3) {
          [0]=>
          string(4) "9999"
          [1]=>
          string(4) "dddd"
          [2]=>
          string(4) "yyyy"
        }
        ["second"]=>
        string(6) "mmgghh"
      }
    }
    ["c"]=>
    string(7) "111-111"
  }
  ["id2"]=>
  array(3) {
    ["a"]=>
    string(7) "888-888"
    ["b"]=>
    array(1) {
      ["666-666"]=>
      array(2) {
        ["first"]=>
        array(3) {
          [0]=>
          string(4) "bbbb"
          [1]=>
          string(4) "cccc"
          [2]=>
          string(4) "7777"
        }
        ["second"]=>
        string(6) "ffffgggg"
      }
    }
    ["c"]=>
    string(7) "555-555"
  }
}
  • 写回答

1条回答 默认 最新

  • doulian1852 2012-06-27 22:42
    关注
    array_walk_recursive($a1,function(&$value,$key,$addin){
            if(is_scalar($value) && isset($addin[$value])){
                    $value = array($value=>$addin[$value]);
            }
       },$b1);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?