使用数据库值创建多维数组

时间:2013-12-09 06:35:16

标签: php arrays multidimensional-array

我有MYSQL查询的结果,如下所示:

    **category_id**  **category_name**  **main_category**
     1            Dancing        Hobbies
     2            Painting       Hobbies
     3            Hip Hop        Music
     4            Jazz           Music

我正在使用MVC框架,查询如下所示:

$db->select(array("a"=>"nesote_matrimony_userinterest","b"=>"nesote_matrimony_category","c"=>"nesote_matrimony_category"));
        $db->fields("a.category_id,b.category_name,b.parent_id,c.category_name,c.parent_id");
        $db->where("a.category_id=b.id and a.user_id=? and c.parent_id=0 and c.id=b.parent_id",$id);
        $db->order("c.category_name asc");

        $interestquery=$db->query();

我需要将查询结果存储为类似

的数组
 array[0][0]= Hobbies

 array[0][1]= Dancing,Painting

 array[1][0]= Music

 array [1][1]= Hip Hop, Jazz

这样我就可以将结果显示为

爱好:跳舞,绘画

在网页中。如何使用PHP从生成的查询结果中创建上述格式的数组?提前谢谢。

3 个答案:

答案 0 :(得分:0)

只需使用mysqli_fetch_assoc

语法:array mysqli_fetch_assoc ( mysqli_result $result )

如果使用PDO,请结帐http://www.php.net/manual/en/pdostatement.fetch.php

例如:

执行某些查询:

喜欢$a=mysqli_query("your select query");

现在为了以多维数组的形式得到结果,你将会写作。

$aa= mysqli_fetch_assoc ( $a );
print_r($aa);//will print the content of the array

while ($row = mysqli_fetch_assoc($aa)) {
    printf ("%s (%s)\n", $row["category_name"], $row["main_category"]);
}

**您可以将其插入数据库。

注意:不要使用mysql_,因为它们已被删除。

答案 1 :(得分:0)

SQL

SELECT 
    group_concat(category_name SEPARATOR ','), main_category
FROM
    test.test
GROUP BY main_category;

PHP

<?php

$host = '';
$dbname = 'test';
$user = 'root';
$password = '';
$dbConnection = new PDO("mysql:host=" . $host . ";
                dbname=" . $dbname . ";charset=utf8", 
                $user, $password, array(
                   PDO::ATTR_PERSISTENT => TRUE
                 ));
$sql = "SELECT 
    group_concat(category_name SEPARATOR ',')as category, main_category as main
FROM
    test.test
GROUP BY main_category;";

$stmt = $dbConnection->prepare($sql);
$stmt->execute();
$stmt->bindColumn('category', $category);
$stmt->bindColumn('main', $main);

while ($stmt->fetch(PDO::FETCH_BOUND)) {
    $list[$main] = $category;
}
echo '<pre>';
print_r($list);

答案 2 :(得分:0)

检查此代码

// this the array from mysql 
$array= array(array('id'=>1,'name'=>'dancing', 'main'=>'hobbies'),    array('id'=>2,'name'=>'paint', 'main'=>'hobbies'), array('id'=>3, 'name'=>'hip    hop','main'=>'music'));


$data= array();
 foreach($array as $key=>$value) {
$data[$value['main']][] = $value['name']; 
}

 // then 
$all = array();
$counter = 0;
foreach($data as $main=>$sub) {
  $all[$counter][0] = $main;
  $all[$counter][1] = implode(',', $sub);
  $counter++;
}
die(print_r($all));