0
我將單詞存儲在一個數組中。每次我從表單添加新單詞時,都會將它們附加到現有數組中。結合array_push和array_flip
我想確保單詞存儲在數組的鍵中,而不是數值。我只是第一次使用array_flip來做,但是當我追加新單詞時,它們會被存儲爲值。
我確定這很簡單,但我怎樣才能確保數組總是被命令將單詞存儲爲鍵?在此先感謝...
這裏是我的代碼:$_SESSION['words']
是單詞的現有陣列和$_POST['additions']
是要添加新傳入的話:
if (isset($_POST['additions']) === true) {
// do cleanup
$additions = explode(",", $_POST['additions']); // create array from $_POST['additions']
$additions = array_map('trim', $additions); // remove whitespace
$additions = array_filter($additions); // remove blank array elements
$additions = preg_replace("/,(?![^,]*,)/",'',$additions); // remove stray characters
foreach($additions as $key => $value) {
// append content to $_SESSION['words']
array_push($_SESSION['words'], $value);
}
// swap all the array values with the array keys
$_SESSION['words'] = array_flip($_SESSION['words']);
// swap keys with values
foreach($_SESSION['words'] as $key => $value) {
$key = $value;
$value = "";
}
非常完美,非常感謝! – matski