PHP - 创建一个从字符串

问题描述:

键值数组我有一个字符串,它看起来像这样:PHP - 创建一个从字符串

$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $';

我需要把它变成一个键值数组。我不在乎过滤和修剪。已经做到了。但我不知道如何获得数组中的键和值。

+1

什么样的字符串是? – Innervisions

+0

究竟应该从这个字符串的键值数组看起来像什么? '1',''''''和'$'的相关性如何? –

移除空键和修剪值使有序的,可用的阵列。

<?php 

$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $'; 

$parts = explode("$",$string); 
$keys = explode("*",substr($parts[0],2)); 
$values = explode("*",$parts[1]); 
$arr = []; 

for ($i = 0; $i < count($keys); $i++) { 
    if (trim($keys[$i]) !== "") { 
     $arr[trim($keys[$i])] = trim($values[$i]); 
    } 
} 
var_dump($arr); 

?> 

绝对没有错误处理,它只会在字符串中的间距一致时才起作用。

$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $'; 

$matches = []; 
preg_match_all('/\* ([^\*]+) /', $string, $matches); 

$keys = array_slice($matches[1], 0, floor(count($matches[1])/2)); 
$values = array_slice($matches[1], ceil(count($matches[1])/2)); 

$result = array_combine($keys, $values); 
var_dump($result); 

这对你来说足够吗?

$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $'; 
$string = str_replace(['1.', ' '], '', $string); // Cleaning unescessary information 

$keysAndValues = explode('$', $string); 

$keys = array_filter(explode('*', $keysAndValues[0])); 
$values = array_filter(explode('*', $keysAndValues[1])); 

$keyPairs = array_combine($keys, $values); 

var_dump($keyPairs); 

阵列(大小= 3)
'KEY1'=>字符串 'VALUE1'(长度= 6)
'KEY2'=> 字符串 '值2'(长度= 6)
'key3'=> string'value3'(length = 6)