简体   繁体   English

使用相同数组索引的不同值从mysql填充php数组

[英]Populate php array from mysql with different values for the same array index

I have a mysql DB with those column id , idUser , idCompany , idProfession for users table. 我有一个针对用户表的列ID,idUser,idCompany,idProfession的mysql数据库。

Now i would Select all those field and make an array that is build in this way : array[idUser] = array [id=> x , idCompany => xx , idProfession => xxx) 现在,我将选择所有这些字段并创建以这种方式构建的数组:array [idUser] = array [id => x,idCompany => xx,idProfession => xxx)

For example 1 user could work for more company and do different profession. 例如,一个用户可以为更多的公司工作并从事不同的职业。 So each array[idUser] Could have multiple array(id, idCompany,idProfession) and i would have 1 result for each idUser instead multiple result for the same idUser. 因此,每个array [idUser]可以具有多个array(id,idCompany,idProfession),并且每个idUser会有1个结果,而同一个idUser会有多个结果。

Now after i did the query i wrote this code but of course id doesnt do what i want becouse it replace always the same element with another one cause the while loop. 现在,在执行查询后,我编写了这段代码,但是id并没有实现我想要的功能,因为它总是将同一元素替换为另一个元素,从而导致while循环。

$data=array();
$sql_result="SELECT etc...........";

    while($rows = mysql_fetch_array($sql_result,MYSQL_BOTH)){
        $data[idUser] = array('idCompany' => $rows['idCompany'], 'profession' => $rows['idProfession'] ); 

I was thinking to do a for loop in the while , store the data in a tmp array. 我当时正在考虑进行for循环,将数据存储在tmp数组中。

But i had to stop becouse i didnt understand how to do that. 但是我不得不停下来,因为我不知道该怎么做。

Does this do what you want? 这是您想要的吗?

$users=array();
$sql_result="SELECT * FROM users";

while($row = mysql_fetch_array($sql_result,MYSQL_BOTH)){
    $users[ $row['idUser'] ][] = array('idCompany' => $row['idCompany'], 'profession' => $row['idProfession'] ); 
}

This will populate the array like this: 这将像这样填充数组:

array(
  idUser => array(
      array('idCompany', 'profession'),
      array('idCompany', 'profession'),
      etc..
     )
)

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

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