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. ...連想配列キーを維持しながら
4

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);

これは、上記のコードと同じ出力を返します。

于 2013-09-30T17:53:28.893 に答える
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;
  } 
于 2013-11-02T04:29:15.287 に答える