2016-12-20 150 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>包含值数组的数组。