2017-03-10 107 views
-1

鍵值數組我有一個字符串,它看起來像這樣:PHP - 創建一個從字符串

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

我需要把它變成一個鍵值數組。我不在乎過濾和修剪。已經做到了。但我不知道如何獲得數組中的鍵和值。

+1

什麼樣的字符串是? – Innervisions

+0

究竟應該從這個字符串的鍵值數組看起來像什麼? '1',''''''和'$'的相關性如何? –

回答

0

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

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

?> 
0

絕對沒有錯誤處理,它只會在字符串中的間距一致時才起作用。

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

這對你來說足夠嗎?

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