简体   繁体   English

如何从MySQL表创建PHP数组

[英]How to create PHP array from MySQL table

I have a MySQL table: 我有一个MySQL表:

-------------------
|type_id|type_name| 
-------------------
|  22   | Toyota  |
|  22   | Mazda   |
|  23   | Volvo   |
|  23   |  Man    |
|  25   | Scania  |
|  25   | Iveco   |
|  25   | Fiat    |
-------------------

which is created dynamically from user input. 它是根据用户输入动态创建的。 I want to create an array from the table using PHP like this: 我想使用PHP从表中创建一个数组,如下所示:

array(
    '22' => array('Toyota', 'Mazda'),
    '23' => array('Volvo', 'Man'),
    '25' => array('Scania', 'Iveco','Fiat'),
);

where array id will be type_id and elements will be type_name's of the type_id.I tried this: 我尝试这样做的地方是:数组ID是type_id,元素是type_id的type_name。

$results = array();
    while($line = mysqli_fetch_array($result, MYSQL_ASSOC))
    {
    $results[] = $line;
    }   
    print_r($results);

But I am getting: 但我得到:

Array ( 
    [0] => Array ( 
            [type_id] => 22 
            [type_name] => Toyota
        ) 
    [1] => Array ( 
            [type_name] => 22 
            [type_name] => Mazda
        )
    ...so on

Please help! 请帮忙!

You need to change your code a bit and it will work fine:- 您需要稍微更改代码,即可正常工作:-

$results = array(); 
while($line = mysqli_fetch_array($result, MYSQL_ASSOC)) { 
  $results[$line['type_id']][] = $line['Type_name'];  //check change here
} 
print_r($results);

Note:- check your column-names and correct them if any mistake is there. 注意:-检查您的列名,如果有任何错误,请更正它们。

Please replace your db name and table name in the code- 请在代码中替换您的数据库名称和表名称-

$conn = mysqli_connect("localhost","root","","dbname");
$query ="select * from table";
$exe = mysqli_query($conn,$query);

$input = array();
$type = array();
while ($result = mysqli_fetch_array($exe)) 
{
    if(array_key_exists($result['type_id'], $input))
    {
        $type[] = $result['type_name'];
    }
    else
    {
        $type = array($result['type_name']);
    }
    $input[$result['type_id']] = $type;
}
echo "<pre>";
print_r($input);

select type_id and Type_name columns from table and in foreach loop do this: 从表中选择type_id和Type_name列,并在foreach循环中执行以下操作:

$output = array();
foreach ($result as $item){
    $output[$item['type_id']][] = $item['Type_name'];
}

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

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