从数据创建数组

时间:2016-12-20 20:03:32

标签: php arrays

我正在尝试从这些数据中创建一个数组,但我得不到它。我尝试使用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>';
?>

2 个答案:

答案 0 :(得分: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
    );
}

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