如何根据特定索引映射两个数组?

时间:2019-03-06 05:49:09

标签: php

Array1 ( [0] => [1] => [2] => 3 [3] => [4] => 5 [5] => [6] => )
Array2 ( [0] => URD [1] => ISL )

我想将$array2的值映射到$array1的索引(值分别为3和5的索引),我想要一个像这样的数组:

Array ( [0] => [1] => [2] => URD [3] => [4] => ISL [5] => [6] => )

我尝试了以下方法:

$newArray = array_values(array_filter(array_merge($array1,$array2)));

但实际结果是:

Array([0] => 3[1] => 5[2] => URD[3] => ISL)

预期结果应该是:

Array ( [0] => [1] => [2] => URD [3] => [4] => ISL [5] => [6] => )

3 个答案:

答案 0 :(得分:1)

代码

尝试以下操作:

<?php

$array1 = ["", "", "3", "", "5", "", ""];
$array2 = ["URD", "ISL"];

foreach($array1 as $id => $a1){
    //for each item in array 1

    if($a1){
        //if the array 1 item has a value

        $array1[$id] = array_shift($array2);
        //replace it with an item from array 2
    }

    if(empty($array2)){
        //if there are no more values left to share in array 2, stop
        break;
    }
}

var_dump($array1);

输出

array(7) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
  [2]=>
  string(3) "URD"
  [3]=>
  string(0) ""
  [4]=>
  string(3) "ISL"
  [5]=>
  string(0) ""
  [6]=>
  string(0) ""
}

注意事项

该方法假定数组1和数组2中都将有值。

一旦数组2中的值被拆分并且数组2为空,则具有设置值的数组1项将不再受到影响。

该方法不在乎在数组1中设置的值是什么,只是在其中一个值。

进一步阅读

foreach()

array_shift()

Codepen

https://3v4l.org/RDQY6

答案 1 :(得分:1)

根据OPS的要求,此解决方案有效且易于理解...

 <?

    $array1 = ["", "", "3", "", "5", "", ""];
    $array2 = ["URD", "ISL"];

    $i =0;
        foreach($array1 as $keys=>$values) {
            if($values == 3 || $values ==5) {
               if(isset($array2[$i])){
                $array1[$keys] = $array2[$i];
                  $i++;
             }else { break; }
           }
         }
    print_R($array1);
    ?>

它将在5和3出现的任何地方替换数组1值中的array2值,而这与它们的排序顺序无关。 例子

$array1 = ["5", "", "3", "", "", "", ""];将被转换为

$array1 = ["URD", "" ,"ISL","","",""];

如果您希望按顺序排列它,那么总是应该先出现3,然后先对array1排序,然后使用我的代码... 如果您想将3替换为URD,将5替换为ISL 那你如果条件会不同

答案 2 :(得分:1)

这是另一种实现方式...(未经测试,但应该可以使用)

<?php

$a = array ( 0 => '', 1 => '', 2 => 3, 3 => '', 4 => 5, 5 => '', 6 => '' );

$b = array ( 0 => 'URD', 1 => 'ISL' );

$c = array_replace ( $a, array_combine ( array_keys ( array_filter ( $a ) ), $b ) );

print_r ( $c );

?>