将数组转换为单个变量

时间:2013-07-17 15:06:53

标签: php simple-html-dom

我使用simplehtmldom来解析网页并提取数据然后将其放入mysql数据库中。我成功地提取了数据并将其放入数组中,但现在我面临的问题是如何将此数组转换为变量,以便我可以在我的数据库查询中使用它来在特定字段中插入记录。我想将数组转换为单个变量

这是代码

<?php
     include("simple_html_dom.php");

     $html = file_get_html('abc.html'); 

     $sched = array();
     foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
         $item['title'] = trim($event->find('td', 1)->plaintext);

         $sched[] = $item;
    }

    var_dump($sched);
?>

,输出

array (size=6)
 0 => 
 array (size=1)
  'title' => string 'Network admin, field engineer, engineering analyst, sales  executive, PA to HR director Required by Telecommunication Company' (length=124)
 1 => 
 array (size=1)
  'title' => string 'Karachi, Hydrabad, Lahore, Rawalpindi, Peshawar, Multan, Faisalabad' (length=67)
 2 => 
 array (size=1)
  'title' => string '5 - 6 Years' (length=11)
 3 => 
 array (size=1)
  'title' => string 'Knowledge of Field' (length=18)
 4 => 
 array (size=1)
  'title' => string '' (length=0)
 5 => 
 array (size=1)
  'title' => string '- Salary and incentives are not full and final. Can be discussed on final interview.

请有人帮助我实现它。提前致谢

5 个答案:

答案 0 :(得分:1)

好吧,如果需要进入特定领域,那么你可以这样做:

INSERT INTO table_name (column1, column2, column3,...)
VALUES ($sched[0]['title'], $sched[1]['title'], $sched[2]['title'],...);

答案 1 :(得分:0)

Php具有获取单个变量的功能extract() http://php.net/manual/en/function.extract.php

但是我不知道为什么你会这样做而不只是使用一个循环来通过你的数组。

答案 2 :(得分:0)

为什么不直接使用数组值?同样对我而言,构建一个每个字段都被称为title的子数组是没有意义的。

$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
    $sched[] = trim($event->find('td', 1)->plaintext);
}

然后访问以下值:

$value0 = $sched[0];
$value1 = $sched[1];

// PDO example
$sth = $dbh->prepare(
    'INSERT INTO table VALUES (?, ?, ...)'
);
$sth->execute(array($sched[0], $sched[1], ...));
// or if array count is right
$sth->execute($sched);

答案 3 :(得分:0)

你的意思是

foreach($sched as $item) {
   $title = $item['title'];
   insert_into_db($title);
}

答案 4 :(得分:0)

为什么要将数据从一个perfectly good位置(即数组)移动到标量变量中。

没有实际原因,将内存使用量增加一倍。

我假设您要将标题存储在表格中

所以你可以:

foreach ( $sched as $one_sched ) {

    // do your database update using $one_sched['title'] as the data identifier.

}
相关问题