2016-12-20 147 views
-1

我想從這個數據創建一個數組,但我不明白。我嘗試使用array_merge函數,但數組構造不正確。這是我的代碼,我想用表格的不同字段創建一個數組。從數據創建數組

<?php 
require('extractorhtml/simple_html_dom.php'); 
$dom = new DOMDocument(); 

//load the html 
$html = $dom->loadHTMLFile("http:"); 


//discard white space 
$dom->preserveWhiteSpace = false; 

//the table by its tag name 
$tables = $dom->getElementsByTagName('table'); 

//get all rows from the table 
$rows = $tables->item(0)->getElementsByTagName('tr'); 
echo '<input type="text" id="search" placeholder="find" />'; 
echo '<table id="example" class="table table-bordered table-striped display">'; 
echo '<thead>'; 
echo '<tr>'; 
echo '<th>Date</th>'; 
echo '<th>Hour</th>'; 
echo '<th>Competition</th>'; 
echo '<th>Event</th>'; 
echo '<th>Chanel</th>'; 
echo '</tr>'; 
echo '</thead>'; 
echo '<tbody>'; 
// loop over the table rows 
foreach ($rows as $row) 
{ 
    // get each column by tag name 
    $cols = $row->getElementsByTagName('td'); 
    // echo the values 
    echo '<tr>'; 
    echo '<td>'.$cols->item(0)->nodeValue.'</td>'; 
    echo '<td>'.$cols->item(1)->nodeValue.'</td>'; 
    echo '<td>'.$cols->item(3)->nodeValue.'</td>'; 
    echo '<td class="text-primary">'.$cols->item(4)->nodeValue.'</td>'; 
    echo '<td>'.$cols->item(5)->nodeValue.'</td>'; 
    echo '</tr>'; 
} 
echo '</tbody>'; 
echo '</table>'; 
?> 
+0

array_merge在哪裏呢?你想在哪裏創建一個數組? –

+0

我想創建一個包含表格的日期,小時,競爭和通道數據的數組,我試着用array_merge,但我不知道如何獲取表格的每個字段的數據並將其正確放入數組 – htmlpower

+0

什麼在'$ tables'中?此外,請展示您的相關嘗試。它幫助我們知道你在想什麼,因爲現在它很不清楚。 – nerdlyist

回答

2

你不需要合併數組,你只需要推入一個新的數組來創建一個2維數組。

$new_array = array(); 
foreach ($rows as $row) 
{ 
    // get each column by tag name 
    $cols = $row->getElementsByTagName('td'); 
    // echo the values 
    echo '<tr>'; 
    echo '<td>'.$cols->item(0)->nodeValue.'</td>'; 
    echo '<td>'.$cols->item(1)->nodeValue.'</td>'; 
    echo '<td>'.$cols->item(3)->nodeValue.'</td>'; 
    echo '<td class="text-primary">'.$cols->item(4)->nodeValue.'</td>'; 
    echo '<td>'.$cols->item(5)->nodeValue.'</td>'; 
    echo '</tr>'; 
    $new_array[] = array(
     'date' => $cols->item(0)->nodeValue, 
     'hour' => $cols->item(1)->nodeValue, 
     'competition' => $cols->item(3)->nodeValue, 
     'channel' => $cols->item(5)->nodeValue 
    ); 
} 
+0

謝謝它現在工作 – htmlpower

1

根據您的<th>值,你知道哪些列包含哪些值,所以它看起來像你只需要修改foreach循環內的代碼追加值到一個數組,而不是產生新的HTML跟他們。

foreach ($rows as $row) 
{ 
    // get each column by tag name 
    $cols = $row->getElementsByTagName('td'); 

    $array['date'] = $cols->item(0)->nodeValue; 
    $array['hour'] = $cols->item(1)->nodeValue; 
    $array['competition'] = $cols->item(3)->nodeValue; 
    $array['event'] = $cols->item(4)->nodeValue; 
    $array['chanel'] = $cols->item(5)->nodeValue; 
    $result[] = $array; 
} 

該循環後,$result將從<td> s,其中每個內部數組代表一個<tr>包含值數組的數組。