dougan4884 2014-11-12 10:07
浏览 33
已采纳

通过保持数组php [关闭]来合并两个数组而不更改键值

I have tree arrays in php as shown in the code

<?php
//old array
$oldArray = array(0 => 11, 1 => 18, 2 => 29, 3 => 35, 4 => 40);

// held values
$hold = array( 1 => 18, 3 => 35);

// new random generated array

$newValues = array( 0 => 27, 1 => 31, 2 => 38);


//I need keep keys (order, index) of $hold values

newArrayMergedPushed = array(0 => 27, 1 => 18, 2 => 31, 3 => 35, 4 => 38);
?>

I need keep order of $hold array in same order,index like in $oldArray. What function can I use in php so that the following output is obtained without changing key values?

  • 写回答

1条回答 默认 最新

  • dozug64282 2014-11-12 10:29
    关注

    If I'm guessing what you want to do correctly, it's probably better to operate directly on the array you want to change rather than creating a range first and then trying to mix them back in.

    Hold only the indexes that you want to keep in a lookup table, then loop over the table and replace any key=>values that aren't held.

    $oldArray = array(0 => 11, 1 => 18, 2 => 29, 3 => 35, 4 => 40);
    $hold = array( 1 => true, 3 => true);
    for( $i = 0; $i < count($oldArray); $i ++ ) {
      if( !isset( $hold[$i] ) ) {
        $oldArray[$i] = mt_rand(0,100); // or whatever you do to generate random numbers
      }
    }
    

    That way you won't have to do any merging at all.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置