0

我将单词存储在数组中。每次我从表单中添加新单词时,它都会将它们附加到现有数组中。

我想确保单词存储在数组的键而不是值中。我只是第一次使用 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 = "";
    }
4

1 回答 1

2

Here you go:

foreach($additions as $key => $value) {     
    // append content to $_SESSION['words']  
    $_SESSION['words'][$value]=count($_SESSION['words'])+1;     
}   

No need to flip around; replace the first foreach loop with this code, and remove everything after it.

于 2012-06-02T11:26:01.290 回答