explode() into $key=>$value pair

后端 未结 15 618
广开言路
广开言路 2020-12-01 09:24

I have this:

$strVar = \"key value\";

And I want to get it in this:

array(\'key\'=>\'value\')

I tried

相关标签:
15条回答
  • 2020-12-01 09:29
    $strVar = "key value";
    list($key, $val) = explode(' ', $strVar);
    
    $arr= array($key => $val);
    

    Edit: My mistake, used split instead of explode but:

    split() function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged

    0 讨论(0)
  • 2020-12-01 09:31

    Try this

    $str = explode(" ","key value");
    $arr[$str[0]] = $str[1];
    
    0 讨论(0)
  • 2020-12-01 09:35

    If you have more than 2 words in your string, use the following code.

        $values = explode(' ', $strVar);
    
        $count = count($values);
        $array = [];
    
        for ($i = 0; $i < $count / 2; $i++) {
            $in = $i * 2;
            $array[$values[$in]] = $values[$in + 1];
        }
    
        var_dump($array);
    

    The $array holds oddly positioned word as key and evenly positioned word $value respectively.

    0 讨论(0)
  • 2020-12-01 09:42

    You can loop every second string:

    $how_many = count($array);
    for($i = 0; $i <= $how_many; $i = $i + 2){
      $key = $array[$i];
      $value = $array[$i+1];
      // store it here
    }
    
    0 讨论(0)
  • 2020-12-01 09:44

    You can try this:

    $keys = array();
    $values = array();
    
    $str = "key value"; 
    $arr = explode(" ",$str);
    
    foreach($arr as $flipper){
       if($flipper == "key"){
          $keys[] = $flipper;
       }elseif($flipper == "value"){
          $values[] = $flipper;
       }
    }
    
    $keys = array_flip($keys);
    // You can check arrays with
    //print_r($keys);
    //print_r($values);
    
    foreach($keys as $key => $keyIndex){
      foreach($values as $valueIndex => $value){
           if($valueIndex == $keyIndex){
              $myArray[$key] = $value;
           }
      }
    }
    

    I know, it seems complex but it works ;)

    0 讨论(0)
  • 2020-12-01 09:45

    Single line for ya:

    $arr = array(strtok($strVar, " ") => strtok(" "));
    
    0 讨论(0)
提交回复
热议问题