简体   繁体   English

PHP从MySQL构建数组

[英]Php Build an Array from MySQL

I currently collect data like this : 我目前正在收集这样的数据:

$query = "SELECT * FROM applicants";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
    echo $row['id'].$row['name'].$row['surname'].$row['email'].$row['dob'];
    echo "<br />";
}

It outputs all the data in one line, like this 它将所有数据输出在一行中,像这样

1maxpaynemax@hat.com24/07/1950

I want to build the data into a Array rather so it looks like this : 我想将数据构建为数组,所以看起来像这样:

$fields = array(
        'id' => '21890',
        'name' => 'nick',
        'surname' => 'moppy',
        'email' => 'nick@moppy.com',
        'dob' => '11-01-1965',

    ),

You should use this way. 您应该使用这种方式。

$query = "SELECT * FROM applicants";

$result = mysql_query($query) or die(mysql_error());

 while($row = mysql_fetch_assoc($result)){
   $res[] = $row;

 }
echo "<pre>"; print_r($res);   echo "</pre>";

You already have your array: 已经有了数组:

$query = "SELECT * FROM applicants";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
    var_dump($row);
}

So I'm going to make an assumption here. 因此,我将在此处进行假设。 That is that you only want id , name , surname , email and dob . 那就是您只需要idnamesurnameemaildob If you want all the columns returned from the table and in the array, just return the SELECT to what it was. 如果要从表和数组中返回所有列,只需将SELECT返回到原来的状态即可。

$query = "SELECT id, name, surname, email, dob FROM applicants";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    // $row is now what your example array looks like
}

So there are 2 differences, first, the specified columns from the table. 因此,有2个区别,首先是表中的指定列。 If you're actually wanting all of the columns returned (back to using * for example), but don't want all of the columns returned in your array, this won't work (but you haven't said either way) but @b0s3 first example will. 如果您实际上要返回所有列(例如,返回*),但又不想在数组中返回所有列,则此方法将不起作用(但您也没有说过) @ b0s3第一个示例将。

Second, the addition of the MYSQL_ASSOC parameter. 其次,添加了MYSQL_ASSOC参数。 This tells PHP to return an array with only the column name indicies as opposed to them AND numeric keys which doubles up the number of items in the array. 这告诉PHP返回一个仅包含列名索引的数组,而不是它们和数字键,这会使数组中的项数加倍。

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

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