简体   繁体   English

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

[英]Reformat array result from php prepared statement

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. 我试图以特定格式将数据输出到数组中,但我坚持使用stmt-> fetch部分以使其以我需要的格式输出数组。

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. 谢谢。

use array_merge_recursive() like this 像这样使用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);
$keys = array_keys($arr[0]);
array_unshift($arr, NULL);
$arr = call_user_func_array('array_map', $arr);
$arr = array_combine($keys, $arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM