簡體   English   中英

如何將包含關聯數組的字符串轉換為關聯數組類型?

[英]How to convert a string that contains an associative array to an associative array type?

我有一個包含這樣的關聯數組的字符串

$string = "['key1'=>'value1','key2'=>'value2','key3'=>'value3']";

我想將其轉換為關聯數組,以便我可以遍歷它。

有什么辦法嗎?

提前致謝 。

非常簡單的方法是將該字符串轉換為json並進行解碼

$string = str_replace(["'", '=>', '[', ']'], ['"', ':', '{', '}'], $string);
print_r(json_decode($string, true));

演示

您可以像這樣使用preg_match_all

$string = "['key1'=>'value1','key2'=>'value2','key3'=>'value3']";

preg_match_all("/'(?P<key>[-\w]+)'\s*=\>\s*'(?P<value>[-\w]+)'/", $string, $matches);

print_r($matches);

輸出:

Array
(
    [0] => Array
        (
            [0] => 'key1'=>'value1'
            [1] => 'key2'=>'value2'
            [2] => 'key3'=>'value3'
        )

    [key] => Array
        (
            [0] => key1
            [1] => key2
            [2] => key3
        )

    [1] => Array
        (
            [0] => key1
            [1] => key2
            [2] => key3
        )

    [value] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )

    [2] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )

)

在這里看到它

需要注意的是[-\\w]+匹配azAZ0-9-_ ,因此這應該是鍵和值的格式。 您當然可以根據需要調整Regx。

現在,如果您想將它們以更實用的格式放置,可以添加以下內容:

 $output = array_combine($matches['key'],$matches['value']);

產量

Array
(
    [key1] => value1
    [key2] => value2
    [key3] => value3
)

我應該指出的一點是,這不適用於嵌套數組,因為您需要更高級的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM