将关联键名对应的数组元素移动到数组的开头

4
到目前为止,我的所有研究都表明,如果不编写冗长的函数(例如这里的解决方案),就无法实现这一点。是否有更简单的方法可以使用预定义的PHP函数来实现呢?
只是为了明确,我正在尝试做以下事情:
$test = array(
    'bla' => 123,
    'bla2' => 1234,
    'bla3' => 12345
);

// Call some cool function here and return the array where the 
// the element with key 'bla2' has been shifted to the beginning like so
print_r($test);
// Prints bla2=1234, bla=>123 etc...

我查看了以下函数,但迄今为止还没有能够自己编写出解决方案。
  1. array_unshift
  2. array_merge

总结

我想要:

  1. 将一个元素移动到数组的开头
  2. ... 同时保留关联数组键
2个回答

8

这对我来说有点滑稽,但是给你:

$test = array(
    'bla' => 123,
    'bla2' => 1234,
    'bla3' => 12345
);

//store value of key we want to move
$tmp = $test['bla2'];

//now remove this from the original array
unset($test['bla2']);

//then create a new array with the requested index at the beginning
$new = array_merge(array('bla2' => $tmp), $test);

print_r($new);

输出结果如下:

Array
(
    [bla2] => 1234
    [bla] => 123
    [bla3] => 12345
)

你可以把这个转化成一个简单的函数,接收一个键和一个数组作为输入,然后输出新排序的数组。
更新:
我不确定为什么我没有使用uksort作为默认值,但你可以更加优雅地完成这个操作。
$test = array(
    'bla' => 123,
    'bla2' => 1234,
    'bla3' => 12345
);

//create a function to handle sorting by keys
function sortStuff($a, $b) {
    if ($a === 'bla2') {
        return -1;
    }
    return 1;
}

//sort by keys using user-defined function
uksort($test, 'sortStuff');

print_r($test);

这段代码返回与上述代码相同的输出结果。

我基本上就是这样做了,但它没有起作用...我一定犯了一个错误。我会再试一次,谢谢 +1 - Ben Carey
@BenCarey 很高兴能帮忙,也请查看更新,或许有更简洁的方法来完成同样的事情。 - Jasper
这可能是我最尴尬的编程错误之一,但我必须承认,我最初编写的代码(与你的完全相同)确实是正确的。然而,我打印的是错误的数组,所以没有看到结果... 太不顺了。感谢你的帮助 :-) - Ben Carey

1

这并不是对Ben问题的严格回答(这样做有问题吗?)- 但这是为将项目列表置于列表顶部而优化的。

  /** 
   * Moves any values that exist in the crumb array to the top of values 
   * @param $values array of options with id as key 
   * @param $crumbs array of crumbs with id as key 
   * @return array  
   * @fixme - need to move to crumb Class 
   */ 
  public static function crumbsToTop($values, $crumbs) { 
    $top = array(); 
    foreach ($crumbs AS $key => $crumb) { 
      if (isset($values[$key])) { 
        $top[$key] = $values[$key]; 
        unset($values[$key]); 
      } 
    } 
    return $top + $values;
  } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接