douyou3619 2013-08-06 04:15
浏览 56
已采纳

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

I'm trying to output data into an array in a specific format but I'm stuck with the stmt->fetch part to get it to output the array in the format I require.

code I have to date (Cobbled together from various online sources)

    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;  
}

Outputs the following:

    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
        )

)

but I want it in the following format:

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
        )
)

I've been trying to achieve this for a while now but I can't seem to get my head around it. Any help would be much appreciated! Thanks.

  • 写回答

2条回答 默认 最新

  • duanci3845 2013-08-06 04:22
    关注

    use array_merge_recursive() like this

    $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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改