php-从字符串创建钥匙值数组



我有一个像这样的字符串:

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

我需要将其转换为键值数组。我不在乎过滤和修剪。已经做到了。但是我不知道如何在数组中获取键和值。

对您来说足够了吗?

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

array(size = 3)
'key1'=> string'value1'(长度= 6)
'key2'=> 字符串'value2'(长度= 6)
'key3'=> string'value3'(长度= 6)

删除空键和 trims 值以制作有序的,可用的数组。

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

最新更新