2

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.

0

1 Answer 1

2

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 ) );
  1. Convert from string to float.
  2. Assign the first array (['first', 'second']) as key to the second array

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,
    },
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey! thank you so much for your help, I am completely new with php, in fact this is my first day giving it a try, so this was really helpful.
Thanks for pointing that out @mickmackusa. I was just assuming that it would only contain 2 floating numbers.
@IsraelChavez Happy to help. :)
@mickmackusa Just accepted the answer, sorry! I did not knew I had to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.