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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里