【问题标题】:Insert element into order position of array?将元素插入数组的顺序位置?
【发布时间】:2011-09-11 19:55:07
【问题描述】:

数组 $A 的所有值都是相同长度的字符串。

$A  = Array
(
    [0] => 03
    [1] => 04
    [2] => 05
    [3] => 06
  //  [4] => 07 // "07" before "04" position
    [4] => 04
    [5] => 05
    [6] => 06
  //   [8] => 07 // "07" before "08" position
    [7] => 08
    [8] => 03
    [9] => 04
    [10] =>  05
    [11] => 06
    [12] => 07 // it is existing
    [13] => 08
) ; 

如果it is not existing 在“04”或“08”位置之前,我想插入“07”元素。从位置1开始

所以改了之后就可以了

$A  = Array
(
    [0] => 03
    [1] => 04
    [2] => 05
    [3] => 06
    [4] => 07 // just appended
    [5] => 04
    [6] => 05
    [7] => 06
    [8] => 07 // just append
    [9] => 08
    [10] => 03
    [11] => 04
    [12] =>  05
    [13] => 06
    [14] => 07
    [15] => 08
) ; 

有人知道怎么做吗,请帮帮我?

【问题讨论】:

  • "append" 表示在末尾插入。你说的是更一般的插入
  • @Tomalak 我确实相信他在更广泛地谈论家庭作业......
  • @newbie 你能解释一下为什么(在我们的预期结果中)07 只是有时在 04 之前被注入,而不是总是?

标签: php arrays


【解决方案1】:

不是最漂亮的解决方案,但应该可以完成工作:

$b = array();
for($i=0;$i<count($A);$i++){
    $b[] = $A[$i];
    if(($i<count($A) - 1) && ($A[$i+1]<$A[$i] || ($A[$i+1] == '08')) && $A[$i] < '07')
        $b[] = '07';
}
var_dump($b);

【讨论】:

  • THANS ,你的条件 if(($i
【解决方案2】:

会有一些“更漂亮”的方法来做到这一点,但正如预期的那样......

  1. 迭代数组
  2. 如果当前值等于 7 减 1,您将在其中插入一个新值
  3. 创建一个函数“insert_into_array”:
    a) 将您的数组一分为二(查看array_chunk
    b) 将您的元素弹出到第一个数组的末尾 (array_pop)
    c) 合并你的两个数组 (array_merge)

我已经放弃编写任何代码,因为这可能是家庭作业,并且编写代码,即使你没有真正深入思考这个问题会推动你通过考试很长的路...

【讨论】:

    【解决方案3】:

    首先,找到你的数组中的空白,即有06但没有跟随07的位置:

    $positions = array();
    foreach ($A as $k => $v) {
        if (isset($last) && $last != $v - 1 && $last == '06') {
            $positions[] = $k;
        }
        $last = $v;
    }
    

    然后,插入它们:

    $count = 0;
    foreach ($positions as $pos) {
        array_splice($A, $pos + ($count++), 0, '07');
    }
    

    就是这样。

    【讨论】:

      【解决方案4】:
      //make sure the array is numeric:
      $A = array_values($A);
      foreach(array('04','08') as $search){
          $positions = array_keys($A,$search);
          rsort($positions);
          foreach($positions as $key){
              if($key==0 || $A[$key-1] != '07'){
                   array_splice($A,$key,0,'O7');
              }
          }
      }
      

      【讨论】:

        【解决方案5】:

        2017 年,我发现了 2 个漂亮的方法,它们是 nette\utils 包的一部分。

        他们做得很好!

        只要运行:

        composer require nette/utils
        

        并在他们的代码中使用Arrays 类或启发。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-03
          • 1970-01-01
          • 2011-03-22
          相关资源
          最近更新 更多