TheRealMrCrowley TheRealMrCrowley - 5 months ago 27
PHP Question

CSV From Nested array

I'm using the medoo framework to interact with MariaDB in PHP.

reults are returned in the following structure:

Array (
[0] => Array (
[Column 0 name] => "VALUE OF Record 0, Column 0"
[0] => "VALUE OF Record 0, Column 0"
[Column 1 name] => "VALUE OF Record 0, Column 1"
[1] => "VALUE OF Record 0, Column 1"
...
...
[Column 99 name] => "VALUE OF Record 0, Column 99"
[99] => "VALUE OF Record 0, Column 99"
)
[1] => Array (
[Column 0 name] => "VALUE OF Record 1, Column 0"
[0] => "VALUE OF Record 1, Column 0"
[Column 1 name] => "VALUE OF Record 1, Column 1"
[1] => "VALUE OF Record 1, Column 1"
...
...
[Column 99 name] => "VALUE OF Record 1, Column 99"
[99] => "VALUE OF Record 1, Column 99"
)
...
...
...
[99] => Array (
[Column 0 name] => "VALUE OF Record 99, Column 0"
[0] => "VALUE OF Record 99, Column 0"
[Column 1 name] => "VALUE OF Record 99, Column 1"
[1] => "VALUE OF Record 99, Column 1"
...
...
[Column 99 name] => "VALUE OF Record 99, Column 99"
[99] => "VALUE OF Record 99, Column 99"
)
)


I need to retrieve the associative keys returned from the user's query (user could put * as a value in SELECT ____ FROM style MySQL Query)

every array has both an associative key and and indexed key value pair for some reason, not 100% why they built it that way. Any suggestions on how to drop all of the indexed results and leave just the associative array?

I'm trying to come up with a way to output the results to CSV.

as you might imagine, fputcsv on the raw data comes out blank;

EDIT
I unset array keys based on if they were integers or not.
All's well that ends well

Ian Ian
Answer

You'll probably need something along these lines. This is on the assumption the data types you outline are accurate

$columns = array(array());
foreach ($arr[0] as $key => $value) {
    if (!is_int($key)) {        
        $columns[0][] = $value;
    }
}

$rows = array();
foreach ($arr as $results) {
    $thisRow = array();
    foreach ($results as $key => $value) {
        if (is_int($key)) {
            $thisRow[] = $value;
        }
    }
    $rows[] = $thisRow;
}

$output = array_merge($columns, $rows);
Comments