2016-12-20 99 views
0

我有一個表格,其行業和類別如下所示。匹配mysql列的多維數組

id|industry|category  | 
1 |Building|Air Conditioning| 
2 |Building|Roofing   | 
3 |Security|Cameras   | 

我想如下

array(
    "Building" => array(
     "Air Conditioning", 
     "Roofing", 
    ), 
    "Security" => array(
     "Cameras", 
    ), 
); 

什麼是接近最好的方法返回一個數組。

感謝您提前提供任何幫助。

回答

0

只是想迭代一次過來的數據:

$data = [ 
    [1, "Building", "Air Conditioning"], 
    [2, "Building", "Roofing"], 
    [3, "Security", "Cameras"] 
]; 
$result = []; 
foreach ($data as $row) { 
    if (!array_key_exists($row[1], $result)) { 
     $result[$row[1]] = []; 
    } 
    array_push($result[$row[1]], $row[2]); 
} 
var_dump($result); 

Link to Fiddle

+0

感謝這是最好的迴應,非常感謝您的瞭解。 –

1

試試這個:

$query = mysql_query('select * from table'); 
foreach ($data = mysql_fetch_object($query)) { 
    $array[$data->industry][] = $data->category; 
} 

print_r($array); 
0
$tbl_industries = array(
    array(
     'id' => 1, 
     'industry' => 'Building', 
     'category' => 'Air Conditioning' 
    ), 
    array(
     'id' => 2, 
     'industry' => 'Building', 
     'category' => 'Roofing' 
    ), 
    array(
     'id' => 3, 
     'industry' => 'Security', 
     'category' => 'Cameras' 
    ) 
); 

foreach($tbl_industries as $industry) { 
    $industry_name = $industry['industry']; 
    $industries[$industry_name][] = $industry['category']; 
} 

var_dump($industries); 

OR

與數據庫交互的代碼:

$con = mysqli_connect('localhost', 'root', '', 'db_name'); 
$query = "SELECT * FROM tbl_industries"; 

if($result = mysqli_query($con, $query)) { 
    while($industry = mysqli_fetch_assoc($result)) { 
     $industry_name = $industry['industry']; 
     $industries[$industry_name][] = $industry['category']; 
    } 

    mysqli_free_result($result);   
    var_dump($industries); 
}