2013-07-17 92 views
1

我正在使用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. 

可以請人可以幫我實現它。在此先感謝

+0

你真正擁有的是一個數組的數組。我不明白你的問題是什麼,因爲你顯然已經知道如何使用foreach結構。也許你可以展示一些你已經嘗試過的代碼,而這些代碼並不是你想做的。 –

回答

1

好吧,如果這需要在特定的領域去,那麼你可以做這樣的事情:

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

感謝Sumoanand多數民衆贊成在我正在尋找。 – ROM

+0

歡迎您:) – Sumoanand

0

PHP已經得到各個變量的函數,extract()http://php.net/manual/en/function.extract.php

但是我不知道爲什麼要那樣做,而不是僅僅使用了一個循環來雖然你的陣列。

+0

「但是我不知道你爲什麼要這樣做,而不是僅僅使用一個循環來通過你的數組。」 - 因爲它更簡單快捷? –

+0

@TerryHarvey全部依賴於數據庫結構。如果每個標題都進入它自己的數組,那麼爲什麼你要寫出一堆不同的查詢,而不是使用循環爲你做呢? – Pitchinnate

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); 
0

你的意思是像somethign

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

0

爲什麼要將數據從一個perfectly good位置即數組移動到標量變量中。

無實際原因使您的內存使用量加倍。

我以爲你會想存儲的標題在表

,因此您可以:

foreach ($sched as $one_sched) { 

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

}