dtfbj24048 2013-10-09 10:06
浏览 21
已采纳

如何在没有手动迭代的情况下交叉多维数组?

I have two multidimensional arrays, example:

array(
  'a' => array(
    'code1' => array('v1', 'v2'),
    'code2' => array('v1', 'v2')
  ),
  'b' => array(
    'code3' => array('v1', 'v2'),
    'code4' => array('v1', 'v2'),
    'code5' => array('v1', 'v2'),
    'code6' => array('v1', 'v2')
  )
)

and

array(
  'a' => array(
    'code1' => '',
  ),
  'b' => array(
    'code5' => ''
  )
)

My desired result is:

array(
  'a' => array(
    'code1' => array('v1', 'v2')
  ),
  'b' => array(
    'code5' => array('v1', 'v2')
  )
)

I'm pretty sure it could be possible using one of built-in php functions, however I'm stuck with it, and can't find a solution rather than manually iterating through array. Can you help me with that?

  • 写回答

1条回答 默认 最新

  • doujiu8826 2013-10-09 10:15
    关注

    The exact solution would depend on what you want to happen if the two arrays don't exactly match key-wise, but one way to reach your desired result is:

    $a = array(
      'a' => array(
        'code1' => array('v1', 'v2'),
        'code2' => array('v1', 'v2')
      ),
      'b' => array(
        'code3' => array('v1', 'v2'),
        'code4' => array('v1', 'v2'),
        'code5' => array('v1', 'v2'),
        'code6' => array('v1', 'v2')
      )
    );
    
    $b = array(
      'a' => array(
        'code1' => '',
      ),
      'b' => array(
        'code5' => ''
      )
    );
    
    $result = array();
    foreach ($a as $key => $data) {
        $result[$key] = array_intersect_key($data, $b[$key]);
    }
    

    The idea is to use array_intersect_key to keep only those elements from $a that appear (as keys) in $b.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类