How to load MySQLi result set into two-dimensional array?

后端 未结 3 884
囚心锁ツ
囚心锁ツ 2021-01-13 08:54

I\'ve got a problem with the mysqli result set. I have a table that contains a bunch of messages. Every table row represents one message. I have a few columns like ID, title

相关标签:
3条回答
  • 2021-01-13 09:03

    You're almost there, you would only need to change a few things:

    $result = $link->query("SELECT * FROM messages WHERE public = '1'");
    $messages = array();
    while($message = $result->fetch_assoc()){
       $messages[] = $message;
    }
    

    This would result in something like this:

    array(
      0 => array('message' => ..., 'subject' => ...), 
      1 => array('message' => ..., 'subject' => ...), 
      2 => array('message' => ..., 'subject' => ...), 
    );
    

    If you want the IDs as the keys, do something like this:

    $messages = array();
    while($message = $result->fetch_assoc()){
       $messages[ $message["id"] ] = $message;
    }
    

    Which would result in:

    array(
      123 => array('message' => ..., 'subject' => ...), 
      456 => array('message' => ..., 'subject' => ...), 
      789 => array('message' => ..., 'subject' => ...), 
    );
    

    In PHP 5.3, you also get a new method, which does the same as the first code example I posted:

    $messages = $result->fetch_all(MYSQLI_ASSOC);
    
    0 讨论(0)
  • 2021-01-13 09:13

    If i get you right, you want to achieve something that is produced by:

    $result = $link->query("SELECT * FROM messages WHERE public = '1'");
    
    $messages = array();
    while($singleMessage = $result->fetch_assoc()){
      $messages[$singleMessage]['title'] = $singleMessage['title'];
      $messages[$singleMessage]['body'] = $singleMessage['body'];
    }
    

    This will get you an 2 dimensional array, using the ID as key.

    0 讨论(0)
  • 2021-01-13 09:24

    How your final array must look like?

    Try this:

    $result = $link->query("SELECT title, body FROM messages WHERE public = '1'");
    $array = array();
    while ($array[] = mysql_fetch_assoc($result)) {}
    
    0 讨论(0)
提交回复
热议问题