38

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:

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.

4

15 回答 15

54

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

list($k, $v) = explode(' ', $strVal);
$result[ $k ] = $v;
于 2013-04-12T08:39:46.373 回答
10
$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
            )
于 2016-12-03T22:09:02.423 回答
4
$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

于 2013-04-12T08:39:13.227 回答
3

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
}
于 2013-04-12T08:39:19.903 回答
3

Try this

$str = explode(" ","key value");
$arr[$str[0]] = $str[1];
于 2013-04-12T08:39:28.813 回答
2
$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.

于 2013-04-12T08:42:45.123 回答
2

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

于 2016-05-15T16:30:52.653 回答
1

Another single line:

parse_str(str_replace(' ', '=', $strVar), $array);
于 2015-09-02T15:24:34.170 回答
1

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.

于 2016-02-19T07:03:36.813 回答
1
list($array["min"], $array["max"]) = explode(" ", "key value");
于 2018-01-17T13:45:49.830 回答
0

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',
]
于 2017-01-24T11:13:15.427 回答
0

If you have more values in a string, you can use array_walk() to create an new array instead of looping with foreach() or for(). I'm using an anonymous function which only works with PHP 5.3+.

// your string
$strVar = "key1 value1&key2 value2&key3 value3";

// new variable for output
$result = array();

// walk trough array, add results to $result
array_walk(explode('&', $strVar), function (&$value,$key) use (&$result) {
    list($k, $v) = explode(' ', $value);
    $result[$k] = $v;
});

// see output
print_r($result);

This gives:

Array
(
    [key1] => value1
    [key2] => value2
    [key3] => value3
)
于 2018-10-11T11:11:38.207 回答
0

I am building an application where some informations are stored in a key/value string.

tic/4/tac/5/toe/6

Looking for some nice solutions to extract data from those strings I happened here and after a while I got this solution:

$tokens = explode('/', $token);

if (count($tokens) >= 2) {
    list($name, $val) = $tokens;
    $props[$name] = $val;
}

if (count($tokens) >= 4) {
    list(, , $name, $val) = $tokens;
    $props[$name] = $val;
}

if (count($tokens) >= 6) {
    list(, , , , $name, $val) = $tokens;
    $props[$name] = $val;
}

// ... and so on

freely inspired by smassey's solution

This snippet will produce the following kinds of arrays:

$props = [
    'tic' => 4,
];

or

$props = [
    'tic' => 4,
    'tac' => 5,
];

or

$props = [
    'tic' => 4,
    'tac' => 5,
    'toe' => 6,
];

my two cents

于 2020-02-27T01:27:12.420 回答
-1

Single line for ya:

$arr = array(strtok($strVar, " ") => strtok(" "));
于 2015-07-20T09:56:17.483 回答
-2

I found another easy way to do that:

$a = array_flip(explode(' ', $strVal));
于 2016-04-08T11:10:47.747 回答