将数组转换为等于关联数组

时间:2017-11-01 20:16:51

标签: php arrays associative-array

我在PHP中有以下数组

array(
  "lat = -0.47023808202763651",
  "lon = -163.04466494518647",
  "alt = 4263.5330573538085",
  "hgt = 0.382990122",
  "nrm = 0.0816367865,0.996595144,-0.0115590692",
  "rot = 0.34263891,-0.470143765,0.647551596,0.492179215",
  "CoM = 0,0,0",
  "stg = 0"
)

我怎么能把它转换成一个关联数组,其中键是等于之前的值,而值是等于之后的值:

array(
  "lat" => "-0.47023808202763651",
  "lon" => "-163.04466494518647",
  "alt" => "4263.5330573538085",
  "hgt" => "0.382990122",
  "nrm" => "0.0816367865,0.996595144,-0.0115590692",
  "rot" => "0.34263891,-0.470143765,0.647551596,0.492179215",
  "CoM" => "0,0,0",
  "stg" => "0"
)

我在这里看过一个数组:Explode a string to associative array但是无法使用此方法转换...

任何提示?示例代码?

2 个答案:

答案 0 :(得分:3)

您需要循环数组并将其展开并创建一个包含键和值的新数组

$new_array = array();
foreach( $array as $value ){
    list($key,$value)=explode('=',$value);
    $new_array[trim($key)] = trim($value);
}
print_r($new_array);

Out put:

Array
(
    [lat] => -0.47023808202763651
    [lon] => -163.04466494518647
    [alt] => 4263.5330573538085
    [hgt] => 0.382990122
    [nrm] => 0.0816367865,0.996595144,-0.0115590692
    [rot] => 0.34263891,-0.470143765,0.647551596,0.492179215
    [CoM] => 0,0,0
    [stg] => 0
)

答案 1 :(得分:0)

        function splitStringsToArray($array) {
            $need = [];
            foreach ($array as $v) {
                list($key, $value) = explode(' = ', $v);
                $need[$key] = $value;
            }

            return $need;
        }

        $arrayYouHave = array(
            "lat = -0.47023808202763651",
            "lon = -163.04466494518647",
            "alt = 4263.5330573538085",
            "hgt = 0.382990122",
            "nrm = 0.0816367865,0.996595144,-0.0115590692",
            "rot = 0.34263891,-0.470143765,0.647551596,0.492179215",
            "CoM = 0,0,0",
            "stg = 0"
        );

        $arrayYouNeed = splitStringsToArray($arrayYouHave);

        print_r($arrayYouHave, $arrayYouNeed);