从php准备语句重新格式化数组结果

时间:2013-08-06 04:15:20

标签: php arrays mysqli prepared-statement

我正在尝试以特定格式将数据输出到数组中,但我坚持使用stmt-> fetch部分来使其以我需要的格式输出数组。

我必须约会的代码(从各种在线资源拼凑而成)

    private function get_results()  
{  
    $parameters = array();
    $results = array();

    $mysqli = new mysqli('localhost', $this->user, $this->pass, $this->db) 
    or die('Problem connecting to the database');

    $stmt = $mysqli->prepare($this->sql) or die('Problem preparing query, check SQL');  
    $stmt->execute();  

    $meta = $stmt->result_metadata();  

    while ( $field = $meta->fetch_field() ) {  

        $parameters[] = &$row[$field->name];

    }  

    call_user_func_array(array($stmt, 'bind_result'), $parameters);  

    while ( $stmt->fetch() ) {  
        $x = array();  
        foreach( $row as $key => $val ) {  
            $x[$key] = $val;  
        }  
        $results[] = $x;  
    }

    $mysqli->close();
    return $results;  
}

输出以下内容:

    Array
(
    [0] => Array
        (
            [Topping] => Mushrooms
            [Slices] => 3
        )

    [1] => Array
        (
            [Topping] => Olives
            [Slices] => 1
        )

    [2] => Array
        (
            [Topping] => Onions
            [Slices] => 1
        )

    [3] => Array
        (
            [Topping] => Pepperoni
            [Slices] => 1
        )

    [4] => Array
        (
            [Topping] => Zuchini
            [Slices] => 2
        )

)

但我希望它采用以下格式:

Array
(
    [Topping] => Array
        (
            [0] => Mushrooms
            [1] => Olives
            [2] => Onions
            [3] => Pepperoni
            [4] => Zuchini
        )

    [Slices] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 1
            [3] => 1
            [4] => 2
        )
)

我一直在努力实现这一目标,但我似乎无法理解它。任何帮助将非常感激!感谢。

2 个答案:

答案 0 :(得分:1)

像这样使用array_merge_recursive()

$ar1=array(array('topping'=>"Mushrooms",'slices'=>"3"),array('topping'=>"Olives",'slices'=>"4"));
$res=array();
foreach($ar1 as $temp)
{
  $res=array_merge_recursive($res, $temp);
}
echo '<pre>';
print_r($res);

答案 1 :(得分:0)

$keys = array_keys($arr[0]);
array_unshift($arr, NULL);
$arr = call_user_func_array('array_map', $arr);
$arr = array_combine($keys, $arr);