2013-08-06 68 views
0

我想輸出數據到特定格式的數組中,但我堅持使用stmt-> fetch部分來讓它以我需要的格式輸出數組。從PHP準備語句重新格式化陣列結果

代碼,我不得不日期(從各種在線資源拼湊)

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

我一直在努力實現這一點,但我似乎無法得到我的頭。任何幫助將非常感激!謝謝。

回答

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); 
0
$keys = array_keys($arr[0]); 
array_unshift($arr, NULL); 
$arr = call_user_func_array('array_map', $arr); 
$arr = array_combine($keys, $arr);