Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have some questions , please help me.

  1. In PHP/MySQL I have a query that I want to generate 2D array, how can I do it ?
  2. I hava a php array code, like this:

    $menu = Array( // I wanna to get data from a SQL SELECT.
        Array('id'=>1,'title'=>'Menu 1',          'parent_id'=>null),
        Array('id'=>2,'title'=>'Sub 1.1',         'parent_id'=>1),
        Array('id'=>3,'title'=>'Sub 1.2',         'parent_id'=>1),
        Array('id'=>4,'title'=>'Sub 1.3',         'parent_id'=>1),
        Array('id'=>5,'title'=>'Menu 2',          'parent_id'=>null),
        Array('id'=>6,'title'=>'Sub 2.1',         'parent_id'=>5),
        Array('id'=>7,'title'=>'Sub Sub 2.1.1',   'parent_id'=>10),
        Array('id'=>8,'title'=>'Sub 2.2',         'parent_id'=>5),
        Array('id'=>9,'title'=>'Menu 3',          'parent_id'=>null),
        Array('id'=>10,'title'=>'Menu 3',          'parent_id'=>null),
    );
    

    How could I to generate this simple array using mysql ?

    <?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Could not connect: " . mysql_error());
    mysql_select_db("mydb");
    
    $result = mysql_query("SELECT * FROM mytable");
    
    //this is wrong,but I wanna to reach this effect↓↓↓↓↓↓↓↓
    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
        echo "Array('id'=>$row["id"],'title'=>'$row["title"]','parent_id'=>$row["parent_id"]),"
    
    }
    
    ?>
    
share|improve this question
add comment

closed as too localized by deceze, hjpotter92, Rachel Gallen, Minko Gechev, tkanzakic Apr 22 '13 at 6:31

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 2 down vote accepted

Create an array with one zero indices and append arrays to it.

$rows = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $rows[] = $row;
}
share|improve this answer
add comment
$data = array();

for ($i=1; $i<4; $i++) {
    $row = array();
    $row[] = $i;
    $row[] = $i*3;
    $row[] = $i*9;

    $data[] = $row;
}

var_dump($data);

--output:--
array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(3)
    [2]=>
    int(9)
  }
  [1]=>
  array(3) {
    [0]=>
    int(2)
    [1]=>
    int(6)
    [2]=>
    int(18)
  }
  [2]=>
  array(3) {
    [0]=>
    int(3)
    [1]=>
    int(9)
    [2]=>
    int(27)
  }
}
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.