0

我已经为我的问题寻找了一个类似的解决方案,但我很难找到它,所以如果已经问过这个问题,请原谅。我有我的php代码

foreach($data['cells'] as $row) {
    print_r($row);
}

产生

Array
(
    [1] => ASSET ID
    [2] => SERIAL IN CAPS
    [3] => COMPANYASSETTAG
    [4] => DATE RCVD
    [5] => MFR
    [6] => Type
    [7] => MODEL
    [8] => PRINTER MODEL COMMENTS
    [9] => PART NUMBER
    [10] => R ID
    [11] => GRADE
    [12] => PRICE
    [13] => COLOR CAPABLE (Color or Monochrome)
    [14] => COSMETICALLY ACCEPTABLE (Yes or No)
    [15] => PRINTERCABLEINCLUDED (Yes or No)
    [16] => PRINTER TECHNOLOGY (Laser, Inkjet, 4-1 Laser, 3-1 Laser, 4-1 Ink Jet, 3-1     Ink Jet, Dot Matrix, Plotter, Solid Ink, Thermal)
    [17] => DUPLEX (Yes or No)
    [18] => MULTIFUNCTION (Yes or No)
    [19] => COMMENT  (reason)
    [20] => COSMETICS COMMENT
    [21] => PURCHASE ORDER # (Trailer #)
    [22] => WAYBILL#
)
Array
(
    [1] => CNGYF04230
    [2] => CNGYF04230
    [3] => MISSING
    [4] => 28/12/2012
    [5] => Hewlett Packard
    [6] => Multi-Function Printers
    [8] => 4345X
    [9] => Q3943A
    [11] => G
    [13] => Monochrome
    [14] => Yes
    [15] => No
    [16] => Laser
    [17] => Yes
    [18] => Yes
    [21] => TRDS293
    [22] => HM693800
)

如您所见,与上述数组相比,第二个数组中的键缺失了。这些对应于列。第二个中缺少一些的原因是因为这些字段不包含任何数据。我希望能够根据键将这些插入到 mysql 表中的相应字段中。

例如

foreach($data['cells'] as $row) {
    //print_r($row);
    $sql = "INSERT INTO table (asset_id,serial_in-caps...) VALUES ('$row[0]','$row[1]'...)";
}
4

3 回答 3

2

由于数组中有数字作为键,因此可以使用 for 循环遍历数组:

$keys = array();
foreach($data["cells"] as $row) {
    if(empty($keys)) {
        $keys = $row;
        continue;
    }

    $rowValues = array();
    for($i = 1; $i < count($keys); $i++) {
        if(isset($row[$i]))
            $rowValues[] = $row[$i];
        else
            $rowValues[] = "NULL"; //(or another standard value)
    }
    /* continue with the variable $rowValues */
}

我希望它有帮助...

于 2012-12-31T22:56:50.020 回答
1

我刚刚找到了解决方案。

foreach($data['cells'] as $row) {
    //print_r($row);
    foreach($row as $key => $value) {
        echo "$key is at $value<br>";
    }
}
于 2012-12-31T22:53:12.767 回答
0

@atreju

你的代码很完美,只是清理了一些丢失的字符:)

$keys = array();
foreach($data["cells"] as $row) {
    if(empty($keys)) {
        $keys = $row;
        continue;
    }

    $rowValues = array();
    for($i = 1; $i <= count($keys); $i++) {
        if(isset($row[$i]))
            $rowValues[] = $row[$i];
        else
            $rowValues[] = "NULL"; //(or another standard value)
        }
    /* continue with the variable $rowValues */
}
于 2013-01-01T01:05:06.713 回答