2014-09-10 118 views
0

我有以下的PHP/MySQL查詢:轉換多維數組到一維使用值從子陣列

$sql = SELECT type, count(*) AS total FROM stats GROUP BY type 
$this->sql = $sql; 

function numObjects() { 

     $stats = $this->conn->query($this->sql); 
     while($stat_type = $stats->fetch_assoc()){ 
      $category[] = $stat_type; 
     } 
     return $category; 
    } 

這是一個簡單的查詢,但我無法弄清楚如何檢索數據的方式我想要,因爲它正在返回一個多維數組。

array(2) { 
    [0]=> array(2) { 
    ["type"]=> string(4) "page" 
    ["total"]=> string(1) "1" 
    } 
    [1]=> array(2) { 
    ["type"]=> string(8) "category" 
    ["total"]=> string(1) "1" 
    } 
} 

我正在做的是將每個數組的值轉換爲key => value對。像這樣:

["page"]=> "1" 
["category"]=> "1" 

我已經能夠將它轉換爲一維數組,但不是正確的格式。

回答

0

試試這個:

$new_array = array(); 
foreach ($old_array as $elem) { 
    $new_array[$elem["type"]] = $elem["total"]; 
} 

var_dump($new_array); //for print the array 
+0

這工作完美。謝謝@heychez! – EternalHour 2014-09-10 23:15:56

0

對於PHP> = 5.5,我給你的array_column()功能

$reformatted = array_column(
    $category, 
    'total', 
    'type' 
); 
+0

我很高興知道這個功能。但問題在於結果是動態的,因此頁面或類別可能並不總是存在。 – EternalHour 2014-09-10 23:04:06

+0

我在編輯後再次嘗試。雖然它看起來應該起作用,但它仍然生成了一個包含2個子數組的多維數組。儘管如此,謝謝,未來會有用。 – EternalHour 2014-09-10 23:20:14