How to transpose MYSQL db in PHP

前端 未结 1 1701
广开言路
广开言路 2021-01-03 17:27

I am using PHP to query a MYSQL db to output data to a csv file.

I am currently able to query the db and export the data to the CSV file.

However i am unabl

相关标签:
1条回答
  • 2021-01-03 17:57

    Try this function:

    function array_transpose($array, $selectKey = false) {
        if (!is_array($array)) return false;
        $return = array();
        foreach($array as $key => $value) {
            if (!is_array($value)) return $array;
            if ($selectKey) {
                if (isset($value[$selectKey])) $return[] = $value[$selectKey];
            } else {
                foreach ($value as $key2 => $value2) {
                    $return[$key2][$key] = $value2;
                }
            }
        }
        return $return;
    }
    
    
    $fruits = array(
        array('id' => 1, 'name' => 'Apple', 'color' => 'Red'),
        array('id' => 2, 'name' => 'Orange', 'color' => 'Orange'),
        array('id' => 3, 'name' => 'Mango', 'color' => 'Yellow')
    );
    echo "<pre>";
    print_r(array_transpose($fruits));
    echo "</pre>";
    

    Returns:

    Array
    (
        [id] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )
    
        [name] => Array
            (
                [0] => Apple
                [1] => Orange
                [2] => Mango
            )
    
        [color] => Array
            (
                [0] => Red
                [1] => Orange
                [2] => Yellow
            )
    
    )
    
    0 讨论(0)
提交回复
热议问题