Reputation: 23
So I have this problem, I am extracting a string from excel that has this structure:
89.356 87.54, 45.34 98.254, 45.2413 45.2146, 98.23 35.647
And I want to build an array with the following structure:
Array
(
[0] => Array
(
['first'] => 89.356
['second'] => 87.54
)
[1] => Array
(
['first'] => 45.34
['second'] => 98.254
)
[2] => Array
(
['first'] => 45.2413
['second'] => 45.2146
)
)
I am extracting these values from an excel and creating the array like this:
$polygons = $sheet->getCell("B".$row)->getValue();
$ret = array_map (
function ($) {return explode (' ', $);},
explode (',', $polygons)
);
But I do not know how to assign the key values 'first' and 'second' to the array.
Upvotes: 2
Views: 50
Reputation: 465
First of all, just to point out that your code will produce an error because you can't create a variable without a name ex. in your code you only have $ as variable.
Here's how you do it.
$ret = array_map( function( $pol ) {
$a = array_map( 'floatval', explode( ' ', $pol, 2 ) ); // 1
return array_combine( ['first', 'second'], $a ); // 2
}, explode( ',', $polygons ) );
Output: var_dump( $ret );
array(3) {
[0] => array(2) {
["first"] => float(89.356),
["second"] => float(89.356),
},
[1] => array(2) {
["first"] => float(45.34),
["second"] => float(98.254),
},
[2] => array(2) {
["first"] => float(45.2413),
["second"] => float(45.2146,
},
}
Upvotes: 2