douan4106 2012-06-02 11:20
浏览 37
已采纳

组合array_push和array_flip

I'm storing words in an array. Every time I add new words from a form, it appends them to the existing array.

I'd like to make sure words are stored in the key of the array and not the value. I just use array_flip to do it the first time, but when I append new words they get stored as values.

I'm sure this is simple, but how can I make sure the array is always ordered to store words as keys?! Thanks in advance...

Here's my code: $_SESSION['words'] is the existing array of words and $_POST['additions'] is the new incoming words to be added:

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 = "";
    }
  • 写回答

1条回答 默认 最新

  • dsh7551 2012-06-02 11:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度