【问题标题】:Convert array to another array将数组转换为另一个数组
【发布时间】:2015-07-27 03:32:07
【问题描述】:

我有一个这样显示的数组:

echo '<table>';
foreach ($rowData as $row => $tr) {
    echo '<tr>'; 
    foreach ($tr as $td)
        echo '<td>' . $td .'</td>';
    echo '</tr>';
}
echo '</table>';

第二列和第四列始终是列的名称。结果是这样的:

姓名:John Locke - 昵称:Locke

年龄:20 - 地址:好的

看到图案了吗?

如何将这些数组放入我的数据库中?


因为我的数据库表结构是:

ID - Name - NickName - Age - Adress

我不知道如何处理我正在使用的数组..

--更新

$table = $html->find('table', 0);
$rowData = array();

foreach($table->find('tr') as $row) {
    // initialize array to store the cell data from each row
    $flight = array();

    foreach($row->find('td') as $cell) {

        foreach($cell->find('span') as $e){
            $e->innertext = '';
        }

        // push the cell's text to the array
        $flight[] = $cell->plaintext;
    }
    $rowData[] = $flight;
}

echo '<table>';
foreach ($rowData as $row => $tr) {
    echo '<tr>'; 
    echo '<td>' . $row . '</td>'; 
    foreach ($tr as $td)
        echo '<td>' . $td .'</td>';
    echo '</tr>';
}
echo '</table>';

【问题讨论】:

    标签: php mysql arrays database


    【解决方案1】:

    你可以这样做:

    $insert = "";
    foreach ($rowData as $row => $tr) {
            $insert .= "('".$tr[0]."','".$tr[0]."','".$tr[0]."','".$tr[0]."'),";
    
    }
    $insert = substr($insert, 0, -1)
    $sql = "Insert into YourTable values ".$insert;
    

    【讨论】:

    • @pbolduc 结果是:插入 myTable 值 ('ID:', '1', 'NAME:' ,'JOHN'), ('NICKNAME:','LOCKE','AGE :','20'); - 如何更改为插入 myTable(ID、NAME、NICKNAME)值('1'、'LOCKE'、..)?
    • 你能告诉我你的阵列我会给你一个更好的解决方案谢谢。我想让你看看你的数组的索引。是数字还是字符串?
    • @pbolduc 你用过 simplehtml dom 解析器吗?当我得到“查找”的返回时,我正在创建数组。我更新了帖子,以便您更好地查看。
    • 不,我从未使用过。我已经更新了我的帖子,尝试将 td 的索引更改为您想要的示例:tr[1] 或 tr[2] ...
    【解决方案2】:

    您已经知道数组位置与什么相关,IE 的位置是 0 到 3。您可以像现在一样简单地迭代并编译查询。

    只需将这个 sn-p 放入您的代码中,我就在运行中将它敲了起来,它有点 hackish,可能是一个更好的方法。只需看看它在屏幕上的作用,看看哪里需要更正。

    $insert = '';
    for ($i=0; $i<=3; $i++):
    
       $insert .= "'" . $tr[$i] . "'";
    
       if ($i !== 3):
           $insert .= ',';
       endif;
    
    endfor;
    
    echo $insert;
    

    一旦您看到看起来像是正确插入的内容,您就可以(使用安全的方法)将其插入到您的数据库中。

    【讨论】:

    • 不知道我的做法是否正确(可能不是),但我得到了很多“$tr[$i],$tr[$i]”。 @克里斯
    • 对不起,我在它周围添加了单引号,这使得 php 逐字阅读。你需要编辑。
    猜你喜欢
    • 1970-01-01
    • 2022-06-17
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多