Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining array with headers - getting empty array

Tags:

arrays

php

I am trying to create a new array where the keys would be the headers from the first array and the values would be all other arrays but I am getting an empty array as a result.

Here is my initial array

$reader = \Asan\PHPExcel\Excel::load('test.xls', function(\Asan\PHPExcel\Reader\Xls $reader){});

foreach ($reader as $row)
{
    print_r($row);
}


Array
(
    [0] => Phone
    [1] => Sum
    [2] => Name
    [3] => Something else
)
Array
(
    [0] => +1 555123456
    [1] => 50.00
    [2] => Johnny Doe
    [3] => 100.50
)
Array
(
    [0] => 911
    [1] => 20.12
    [2] => Eli the Computer Guy
    [3] => 99.99
)

I tried to create the new array like this

$row = 1; // header row
foreach ($reader as $row)
{
    if ($row == 1)
    {
        $headers = $row;
    }
    else
    {
        $new_array[] = [
            $headers => $row;
        ]
    }

    print_r($row); // prints empty array
}

I would like the result array to look like this

Array
(
    [0] => Array
        (
            [Phone] => +1 555123456
            [Sum] => 50.00
            [Name] => Johnny Doe
            [Something else] => 100.50
        )

    [1] => Array
        (
            [Phone] => 911
            [Sum] => 20.12
            [Name] => Eli the Computer Guy
            [Something else] => 99.99
        )
)
like image 988
Liga Avatar asked May 30 '26 02:05

Liga


2 Answers

You can also use array_map and array_combine:

$headers = array_shift($arrays);
$result = array_map(function($x) use ($headers){
    return array_combine($headers, $x);
}, $arrays);

Demo

like image 179
The fourth bird Avatar answered Jun 01 '26 15:06

The fourth bird


You are overwriting your row counter $row with values from the reader: foreach ($reader as $row). You are also missing an increment on the row counter. Having fixed those issues, you can use array_combine to solve your problem:

$row = 1; // header row
$new_array = array();
foreach ($reader as $data)
{
    if ($row == 1)
    {
        $headers = $data;
    }
    else
    {
        $new_array[] = array_combine($headers, $data);
    }
    $row++;
}
print_r($new_array);

Demo on 3v4l.org

like image 40
Nick Avatar answered Jun 01 '26 15:06

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!