PHP数组在两个数组之间交换键值

时间:2020-04-21 11:59:53

标签: php arrays

我有2个数组

array (
  0 => 'END PIECE',
  1 => 'END PIECE',
  2 => 'END PIECE',
  3 => 'Title translation test 2',
  4 => 'Title translation test 2',
  5 => 'PIÈCE D\'EXTRÉMITÉ'
);

array (
  0 => '47933',
  1 => '47935',
  2 => '47936',
  3 => '47929',
  4 => '47930',
  5 => '47933'
);

我想从这2个数组中创建一个数组,例如

array (
  'END PIECE' => '47933',
  'END PIECE' => '47935',
  'END PIECE' => '47936',
  'Title translation test' => '47929',
  'Title translation test' => '47930',
  'PIÈCE D\'EXTRÉMITÉ' => '47933'
);

有可能吗?需要PHP 5.3版本,我已经尝试过

$c = array();
foreach($arr1 as $k => $val){
    $c[] = array($arr2[$k] => $val);
}

但这不起作用

2 个答案:

答案 0 :(得分:2)

有两种方法可以完成此操作,简单版本将始终具有子数组...

$c = array();
foreach($arr1 as $k => $val){
    $c[$arr2[$k]][] = $val;
}

print_r($c);

给予...

Array
(
    [END PIECE] => Array
        (
            [0] => 47933
            [1] => 47935
            [2] => 47936
        )

    [Title translation test 2] => Array
        (
            [0] => 47929
            [1] => 47930
        )

    [PIÈCE D'EXTRÉMITÉ] => Array
        (
            [0] => 47933
        )

)

如果您只希望重复项具有子数组,那么您需要在添加新项时检查是否已设置该项并且已经是数组,并在进行时进行调整...

$c = array();
foreach($arr1 as $k => $val){
    if ( isset ($c[$arr2[$k]])) {
        if ( !is_array($c[$arr2[$k]]) )
            $c[$arr2[$k]] = [$c[$arr2[$k]]];
        $c[$arr2[$k]][] = $val;
    }
    else    {
        $c[$arr2[$k]] = $val;
    }
}
print_r($c);

给予...

Array
(
    [END PIECE] => Array
        (
            [0] => 47933
            [1] => 47935
            [2] => 47936
        )

    [Title translation test 2] => Array
        (
            [0] => 47929
            [1] => 47930
        )

    [PIÈCE D'EXTRÉMITÉ] => 47933
)

如您所见,PIÈCED'EXTRÉMITÉ元素在两种情况下都是不同的。

答案 1 :(得分:1)

您可以使用array_combine()函数(PHP 5,PHP 7),如下所示

response = self.client.post(
        reverse('edit_form', kwargs={'pk': self.instance.id}),
        data={'id': self.instance.id,
              'comment':self.instance.comment.id,
              'sequence': self.instance.sequence.id,
               #more fields omitted
        })

输出:

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);