PHP: Convert comma separated value pair string to Array

后端 未结 2 1209
悲&欢浪女
悲&欢浪女 2021-01-25 09:17

I have comma separated value pairs and I would like to convert it to associative array in php.

Example:

{ 
   Age:30,
   Weight:80,
   Height:180
}
         


        
2条回答
  •  无人及你
    2021-01-25 09:25

    You can get all values in an array by using this basic example:

    // your string
    $string = "{ 
       Age:30,
       Weight:80,
       Height:180
    }";
    
    // preg_match inside the {}
    preg_match('/\K[^{]*(?=})/', $string, $matches);
    
    $matchedResult = $matches[0];
    $exploded = explode(",",$matchedResult); // explode with ,
    
    $yourData = array();
    foreach ($exploded as $value) {
        $result = explode(':',$value); // explode with :
        $yourData[$result[0]] = $result[1];
    }
    
    echo "
    ";
    print_r($yourData);
    

    Result:

    Array
    (
        [Age] => 30
        [Weight] => 80
        [Height] => 180
    )
    

    Explanation:

    1. (?<=}) look behind asserts.
    2. K[^{] matches the opening braces and K tells what was matched.

提交回复
热议问题