【问题标题】:replace the word in the array with given value用给定值替换数组中的单词
【发布时间】:2020-10-08 13:09:45
【问题描述】:

我有数组变量$geo_detail=Array ( [0] => nsu [1] => us east [2] => us west ) 我想替换nsu with NSU,us east to US Eastus west to US West

我试过了

if (count($geo_detail))
          {
              foreach($geo_detail as $geos=>$key){
                  if (str_word_count($key) =='1')
                     $key= strtoupper($key);
                  elseif((str_word_count($key) =='2'))
                   $key= ucwords($key); 
              }
          }
         return $geo_detail;

但返回Array ( [0] => nsu [1] => us east [2] => us west )

如何替换数组值

【问题讨论】:

    标签: php arrays string


    【解决方案1】:

    您需要从数组中更改真正的键/值,替换

    $key= strtoupper($key);
    

    geo_detail[$geos] = strtoupper($key);
    

    $key= ucwords($key); 
    

    geo_detail[$geos] = ucwords($key);
    

    【讨论】:

    • 修改后的结果是数组 (3) {[0] => string (3) "NSU" [1] => string (7) "Us East" [2] => string (7) "Us West"} 而不是任务要求的美国东部和美国西部!
    • 这是更新他的数组,而不是做他关于大写的工作
    【解决方案2】:
    $geo =  ['nsu', 'us west', 'us east'];
    
    foreach ($geo as $k => $g) {
        
        // explode string
        $words = explode(" ", $g);
        
        $string = "";
        foreach($words as $w) {
            
            // 3 chars and below, all caps
            if (strlen($w) <= 3) {
                $w = strtoupper($w);
            } else {
                
                $w = ucwords($w);
            }
            
            $string = $string . $w . " ";
        }
        
        
        // assign new value, remove space at end
        $geo[$k] = substr($string, 0, -1);
    }
    
    print_r($geo);
    

    结果

    Array ( [0] => NSU [1] => US West [2] => US East )
    

    【讨论】:

      【解决方案3】:

      这些词必须分开处理。我对任务的理解如下:

      第一个单词全部大写,第二个单词只有第一个字母。

      我也使用了explode() 进行拆分。

      $geo_detail = ['nsu','us east','us west'];
      
      $result = [];
      foreach($geo_detail as $key => $item){
        $wordArr = explode(' ',$item);
        $new = strtoupper($wordArr[0]);
        if(isset($wordArr[1])){
          $new .= " ".ucwords($wordArr[1]);
        }
        $result[$key] = $new;
      }
      
      $expected = ['NSU','US East','US West'];
      var_dump($result === $expected);//bool(true)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-25
        • 2022-01-25
        • 2020-07-13
        • 2020-02-05
        • 1970-01-01
        • 2012-09-06
        • 2015-09-06
        • 2023-04-06
        相关资源
        最近更新 更多