【问题标题】:How do I move an array element with a known key to the end of an array in PHP?如何在 PHP 中将具有已知键的数组元素移动到数组的末尾?
【发布时间】:2011-01-22 12:17:13
【问题描述】:

因为一个相当微不足道的问题而大脑冻结。如果我从这样的数组开始:

$my_array = array(
                  'monkey'  => array(...),
                  'giraffe' => array(...),
                  'lion'    => array(...)
);

...并且新元素可能会添加不同的键,但始终是数组值。现在我可以确定第一个元素总是会有键“monkey”,但我不能确定其他任何键。

当我完成数组的填充后,我想将已知元素“猴子”移动到数组的末尾,而不会干扰其他元素的顺序。最有效的方法是什么?

我能想到的每一种方式都显得有些笨拙,而且我觉得我错过了一些明显的东西。

【问题讨论】:

    标签: php arrays sorting


    【解决方案1】:

    在 foreach 循环中使用数组索引有条件地执行此操作:

    $i = 0;
    foreach( $items as $item ) {
        if ( $item->Value === 0 ) { // the condition I'm using, you can do whatever
            $item_to_move = $items[$i]; // pick out our item
            unset( $items[$i] ); // take it out of the array
            array_push( $items, $item_to_move); // re-add it (at the end)
        }
        $i++;
    }
    

    【讨论】:

    • 这个问题(来自十多年前)专门询问关联数组并在具有已知键的元素上进行操作。此代码不相关。
    【解决方案2】:

    基于@cletus 的回答,我在 foreach 中使用它来删除特定元素的重复项,并将第一次出现的元素移动到数组的末尾,如下所示:

    foreach($ievent as $k => $ev) {
        
        //make other operations in my foreach           
        ...
                        
        //Delete duplicate CLOSE event
        if($ev['event'] == 'close') {
            if(!$close) {
                $close = $ievent[$k];
            }
            unset($ievent[$k]);
        }           
    }
                    
    //Add first 'close' element to end of array
    $ievent[] = $close;
    

    【讨论】:

    • 这与问题无关,该问题与关联数组的单个元素有关。
    • 其实是这样。我对我的数组进行了多次操作,其中一个是基于@Cletus 的回答,感谢他。就我而言,关键是子数组的“关闭”值。
    【解决方案3】:

    我真的很喜欢上面@Gordon 的回答,因为它作为一个单行列很优雅,但它只有在关键位于开头时才有效。这是另一种适用于任何位置的键的衬垫:

    $arr = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
    $arr += array_splice($arr,array_search('giraffe',array_keys($arr)),1);
    

    编辑:请注意,使用数字键会失败。

    【讨论】:

      【解决方案4】:

      您可以实现一些基本的演算并获得一个通用函数,用于将数组元素从一个位置移动到另一个位置。

      对于 PHP,它看起来像这样:

      function magicFunction ($targetArray, $indexFrom, $indexTo) { 
          $targetElement = $targetArray[$indexFrom]; 
          $magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom); 
      
          for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){ 
              $targetArray[$Element] = $targetArray[$Element + $magicIncrement]; 
          } 
      
          $targetArray[$indexTo] = $targetElement; 
      }
      

      查看“gloommatter”中的“移动数组元素”了解详细说明。

      http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html

      【讨论】:

      • 问题是关于将单个元素从关联数组移动到该数组的末尾。此代码与此无关。
      【解决方案5】:

      array_shift 的效率可能低于unsetting the index,但它确实有效:

      $my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
      $my_array['monkey'] = array_shift($my_array);
      print_r($my_array);
      

      另一种选择是使用回调和uksort

      uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
      

      如果您使用的是 PHP5.3+,您将需要使用正确的 lambda,或者只是将函数定期定义为全局函数。

      【讨论】:

      • 两个很好的答案。那种是我想到的,但它似乎有点矫枉过正。
      • @tamewhale 谢谢。我用 24 只动物做了一个非常肤浅的基准测试,unset 确实是最快的。比array_shift快10倍,比uksort快300倍。
      • 喜欢一个班轮 - 可能不是最有效的,但在大多数情况下它永远不会重要,array_shift() 方法的优雅使其干净易读。
      • 第一个使用 array_shift 的解决方案仅适用于数组的第一个元素。
      【解决方案6】:

      我能想到的唯一方法是删除它然后添加它:

      $v = $my_array['monkey'];
      unset($my_array['monkey']);
      $my_array['monkey'] = $v;
      

      【讨论】:

      • 是的,这可能是最好的方法。我可能想太多了。
      • @RolandSeuhs 究竟是什么在 PHP 7.1 中不起作用?它似乎对我来说很好。
      • 当我测试它时,元素被插入到与原来相同的位置而不是最后,对我来说看起来像是一些缓存功能,但我可能错了。
      猜你喜欢
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多