如何相互置换两个数组键

时间:2015-12-02 16:08:19

标签: php arrays permutation

如何将一个数组中的每个值与另一个数组合并创建一个可作为表源的结构。 例如,我们有数组:

$a = array(
  'animal' => ['horse', 'donkey', 'elephant'],
  'food' => ['grass', 'hay', 'acorn'],
);

And the effect I need is:

$result = array(
  'horse' = array(
    'grass' => [ 'animal' => 'horse', 'food' => 'grass'],
    'hay' => [ 'animal' => 'horse', 'food' => 'hay'],
    'acorn' => [ 'animal' => 'horse', 'food' => 'acorn'],
  },
  'donkey' = array(
    'grass' => [ 'animal' => 'donkey', 'food' => 'grass'],
    'hay' => [ 'animal' => 'donkey', 'food' => 'hay'],
    'acorn' => [ 'animal' => 'donkey', 'food' => 'acorn'],
  },
  'elephant' = array(
    'grass' => [ 'animal' => 'elephant', 'food' => 'grass'],
    'hay' => [ 'animal' => 'elephant', 'food' => 'hay'],
    'acorn' => [ 'animal' => 'elephant', 'food' => 'acorn'],
  },
);

但我的问题是也可以将算法推广到任意高维度。

1 个答案:

答案 0 :(得分:2)

就算法而言,我会说你自己尝试一些东西。

话虽如此,我建议从嵌套的foreach循环开始:

$result = array();

foreach ($a['animal'] as $val) {
    $result[$val] = array();
    foreach ($a['food'] as $val2) {
        $result[$val][$val2] = array('animal' => $val, 'food' => $val2);
    }
}

然后可以将此代码扩展为模块化/可自定义。