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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度