2

是否可以将这种数据从数据库插入到数组中?

Mouse
Keyboard  //Saved from a Textarea box 
Monitor

整张桌子是这样的;

id  ||   Owner  ||  Items
--------------------------
1   ||   John   || Mouse
    ||          || Keyboard //This is in a single row
    ||          || Monitor
--------------------------

如何将字段“Items”中的每一行数据分配到一个数组中(比如说$items)?

所以它会像:

  $items[0] = "Mouse";
  $items[1] = "Keyboard";
  $items[2] = "Monitor";
4

4 回答 4

4

尝试:

$items = explode("\n", $string_from_db);
于 2012-05-23T04:51:57.540 回答
0

您可以使用mysql_fetch_assoc()

PDOStatement::fetchAll()

mysqli_result::fetch_assoc()

于 2012-05-23T03:50:13.727 回答
0

像这样的东西?

$arr = explode("\n",$data);   // split into lines
$categories = explode("||",$arr[0]);
unset($arr[0]); array_values($arr[0]);  // dont want categories anymore
array_walk($categories,create_function('&$v','$v = trim($v);'));   // trim space from categories
$data = array();   // holds info
foreach((array)$arr as $key=>$val) {
   if (substr($val,0,5)=="-----") { continue; }   // ignore "-----..." lines
   $row = explode("||",$val);
   foreach((array)$row as $key2=>$val2) {
      $data[ $categories[$key2] ][] = trim($val2);
   }
}

echo "<pre>";
print_r($data);
echo "</pre>";

您使用上述代码的示例给出:

Array
(
    [id] => Array
        (
            [0] => 1   
            [1] =>     
            [2] =>     
        )

    [Owner] => Array
        (
            [0] =>    John   
            [1] =>           
            [2] =>           
        )

    [Items] => Array
        (
            [0] =>  Mouse
            [1] =>  Keyboard
            [2] =>  Monitor
        )

)
于 2012-05-23T03:53:19.380 回答
0

如果我正确阅读最后一行,你想要:

  $results = $db -> query("SELECT Items FROM table");

  while($row = $results -> fetch_assoc()) {
        $items[] = $row['Items'];
  }
于 2012-05-23T04:55:00.480 回答