php 爆炸()到 $key=>$value 对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15966693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:17:31  来源:igfitidea点击:

explode() into $key=>$value pair

php

提问by Borniet

I have this:

我有这个:

$strVar = "key value";

And I want to get it in this:

我想得到它:

array('key'=>'value')

I tried it with explode(), but that gives me this:

我用explode()试过了,但这给了我这个:

array('0' => 'key',
      '1' => 'value')

The original $strVar is already the result of an exploded string, and I'm looping over all the values of the resulting array.

原始的 $strVar 已经是分解字符串的结果,我正在遍历结果数组的所有值。

回答by smassey

Don't believe this is possible in a single operation, but this should do the trick:

不要相信这在单个操作中是可能的,但这应该可以解决问题:

list($k, $v) = explode(' ', $strVal);
$result[ $k ] = $v;

回答by Alienoiduk

$my_string = "key0:value0,key1:value1,key2:value2";

$convert_to_array = explode(',', $my_string);

for($i=0; $i < count($convert_to_array ); $i++){
    $key_value = explode(':', $convert_to_array [$i]);
    $end_array[$key_value [0]] = $key_value [1];
}

Outputs array

输出数组

$end_array(
            [key0] => value0,
            [key1] => value1,
            [key2] => value2
            )

回答by iiro

$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

自 PHP 5.3.0 起,split() 函数已被弃用。非常不鼓励依赖此功能

回答by Voitcus

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
}

回答by chandresh_cool

Try this

尝试这个

$str = explode(" ","key value");
$arr[$str[0]] = $str[1];

回答by Martin Prikryl

$pairs = explode(...);
$array = array();
foreach ($pair in $pairs)
{
    $temp = explode(" ", $pair);
    $array[$temp[0]] = $temp[1];
}

But it seems obvious providing you seem to know arrays and explode. So there might be some constrains that you have not given us. You might update your question to explain.

但如果您似乎知道数组和explode. 所以可能有一些你没有给我们的限制。您可能会更新您的问题以进行解释。

回答by Utku Korkmaz

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 ;)

我知道,这看起来很复杂,但确实有效;)

回答by AbraCadaver

Another single line:

另一行:

parse_str(str_replace(' ', '=', $strVar), $array);

回答by Eranda

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

如果您的字符串中有 2 个以上的单词,请使用以下代码。

    $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 $arrayholds oddly positioned word as keyand evenly positioned word $valuerespectively.

分别$array持有奇数定位词key和偶数定位词$value

回答by winkbrace

If you have long list of key-value pairs delimited by the same character that also delimits the key and value, this function does the trick.

如果您有很长的键值对列表,这些键值对由同样分隔键和值的相同字符分隔,则此函数可以解决问题。

function extractKeyValuePairs(string $string, string $delimiter = ' ') : array
{
    $params = explode($delimiter, $string);

    $pairs = [];
    for ($i = 0; $i < count($params); $i++) {
        $pairs[$params[$i]] = $params[++$i];
    }

    return $pairs;
}

Example:

例子:

$pairs = extractKeyValuePairs('one foo two bar three baz');

[
    'one'   => 'foo',
    'two'   => 'bar',
    'three' => 'baz',
]