-2

I have the following array in 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"
)

How could I convert this to an associative array where the keys are what's before equals and the values are what's after the equals:

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

I have seen walking an array here: Explode a string to associative array But have been unable to convert using this method...

Any tips? Sample code?

logo3801
  • 85
  • 9

2 Answers2

3

You need to loop the array and explode it and create an new array with key and value

$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
)
Ravinder Reddy
  • 3,869
  • 1
  • 13
  • 22
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);
Lexxusss
  • 542
  • 4
  • 10