如何在 PHP 中将数组中一个元素的值替换为另一个数组的值


How to replace values of one element in array with values from another array in PHP?

如果我有这样的主数组:

array(5) {
  [0]=>
  string(4) "1039"
  [1]=>
  string(1) "1"
  [2]=>
  string(4) "2015"
  [3]=>
  string(1) "0"
  [4]=>
  string(0) ""
}
array(5) {
  [0]=>
  string(4) "1040"
  [1]=>
  string(1) "1"
  [2]=>
  string(4) "2015"
  [3]=>
  string(1) "0"
  [4]=>
  string(0) ""
}
array(5) {
  [0]=>
  string(4) "1041"
  [1]=>
  string(1) "1"
  [2]=>
  string(4) "2015"
  [3]=>
  string(1) "0"
  [4]=>
  string(0) ""
}

我想用另一个数组中的值替换每个第 4 个键值。

第二个数组是:

array(156) {
  [0]=>
  string(12) "Some title 1"
  [1]=>
  string(12) "Some title 2"
  [2]=>
  string(12) "Some title 3"
}

所以新数组应该看起来像这样:

array(5) {
  [0]=>
  string(4) "1039"
  [1]=>
  string(1) "1"
  [2]=>
  string(4) "2015"
  [3]=>
  string(1) "Some title 1"
  [4]=>
  string(0) ""
}
array(5) {
  [0]=>
  string(4) "1040"
  [1]=>
  string(1) "1"
  [2]=>
  string(4) "2015"
  [3]=>
  string(1) "Some title 2"
  [4]=>
  string(0) ""
}
array(5) {
  [0]=>
  string(4) "1041"
  [1]=>
  string(1) "1"
  [2]=>
  string(4) "2015"
  [3]=>
  string(1) "Some title 3"
  [4]=>
  string(0) ""
}

如何实现这一点?我尝试过第一个 foreach 循环,然后在第二个 foreach 里面循环,然后是 string_replacearray_replace 之类的东西,但从未让它工作。提前致谢

if($masterArray) {
  foreach($masterArray as $mKey=>$mValue) {
    if(isset($secondArray[$mKey]) {
      $masterArray[$mKey][3] = $secondArray[$mKey];
     }
  }
}

只需使用您可以索引的事实。

for($i = 0; $i < count($second_array); $i++)
{
    $array_to_update = $arraylist[$i]; //get one of the arrays that you want to update
    $array_to_update[3] = $second_array[$i]; // 0-based index, so [3] is actually your 4th value. Set it to the $i-th value in your second array.
}

多内斯基的。

注意:我假设您在称为arraylist的其他阵列中具有要更新的阵列。如果您没有该格式,请将其设置为那样或使用其他方法。另外,我假设数组列表和second_array(包含要添加的字符串)的长度相同。如果不是这种情况,请确保不会使索引超出界限错误。

if(count($masterArr) > 0) {
  foreach($masterArr as $key => $value) {
    if( isset($masterArr[$key][3]) && isset($secondArr[$key]) {
      $masterArr[$key][3] = $secondArr[$key];
      continue; # Will help to neglect unwanted loops 
    }
  }
}

在您的情况下,您可以使用以下代码:

$myArray = array_replace($myArray ,array_fill_keys(array_keys($myArray , $value),$replacement));