douguai4653 2016-01-18 10:08
浏览 48
已采纳

如何用PHP中另一个数组的值替换数组中一个元素的值?

If I have master array like this:

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) ""
}

I want to replace every 4th key value with the value from another array.

Second arrays is:

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

So the new array should look like this:

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) ""
}

How this can be achieved ? I have tried looping with foreach for the first one and then inside again foreach for the second one, and then string_replace, array_replace and stuff like that, but never got it to work. Thanks in advance

  • 写回答

4条回答 默认 最新

  • dongre9937 2016-01-18 10:16
    关注
    if($masterArray) {
    
      foreach($masterArray as $mKey=>$mValue) {
        if(isset($secondArray[$mKey]) {
          $masterArray[$mKey][3] = $secondArray[$mKey];
         }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?