【问题标题】:Move array element with specific key to beginning of array将具有特定键的数组元素移动到数组的开头
【发布时间】:2018-09-28 10:27:30
【问题描述】:

我找不到关于这个的东西,可能我错过了,但我想过滤/排序一个数组,它有一个我想移到顶部的键,所以它将是第一项。在我的示例中,我希望键 3 移到顶部。有没有简单的方法可以做到这一点?

// at default
[    
"key 1" : [ more data ],
"key 2" : [ even more data ],
"key 3" : [ some data ],// for this example I want this to be the first item
"key 4" : [ where is the data ]
]

// how i want it to be

move_to_first_in_array($array , 'key 3');

[  
"key 3" : [ some data ],// for this example I want this to be the first item  
"key 1" : [ more data ],
"key 2" : [ even more data ],
"key 4" : [ where is the data ]
]

【问题讨论】:

  • 您必须提供过滤数组的条件
  • 不,它不是重复的
  • @user759235 但为什么不是......这就是你想要的?
  • 我现在提供了一个例子

标签: php


【解决方案1】:
function move_to_first_in_array($array, $key) {
  return [$key => $array[$key]] + $array;
}

这使用+ 运算符返回两个数组的并集,左侧操作数中的元素优先。 From the documentation:

+ 运算符返回附加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而忽略右侧数组中的匹配元素。

https://3v4l.org/ZQV2i

【讨论】:

  • 你有点快,所以我再次删除了我的答案(说的基本相同);-)
【解决方案2】:

怎么样:

function move_to_first_in_array(&$array, $key)
{
    $element = $array[$key];
    unset($array[$key]);
    $array = [$key => $element] + $array;
}

真的很丑,但是很管用。

【讨论】:

    【解决方案3】:

    以这种方式也尝试核心 PHP。

    <?php
    
    $array = array(    
    "key 1" => " more data ",
    "key 2" => "even more data",
    "key 3" => "some data ",// for this example I want this to be the first item
    "key 4" => "where is the data"
    );
    echo "<pre>";print_r($array);
    echo "<br>";
    
    
    $array2 = array("key 3","key 1","key 2","key 4");
    
    $orderedArray = array();
    foreach ($array2 as $key) {
        $orderedArray[$key] = $array[$key];
    }
    
    echo "<pre>";print_r($orderedArray);exit;
    
    ?>
    

    答案:

    Array
    (
        [key 1] =>  more data 
        [key 2] => even more data
        [key 3] => some data 
        [key 4] => where is the data
    )
    
    Array
    (
        [key 3] => some data 
        [key 1] =>  more data 
        [key 2] => even more data
        [key 4] => where is the data
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-29
      • 2023-01-11
      • 1970-01-01
      • 2021-11-27
      • 2022-11-14
      • 1970-01-01
      • 2011-01-22
      • 2017-05-13
      相关资源
      最近更新 更多