将包含数据库空间的数据插入数组

时间:2012-05-23 03:35:02

标签: php mysql

是否可以将此类数据从数据库插入数组?

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 个答案:

答案 0 :(得分:4)

尝试:

$items = explode("\n", $string_from_db);

答案 1 :(得分:0)

答案 2 :(得分: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
        )

)

答案 3 :(得分:0)

如果我正确读取最后一行,您需要:

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

  while($row = $results -> fetch_assoc()) {
        $items[] = $row['Items'];
  }