我已经为我的问题寻找了一个简单的解决方案,但我很难找到它,所以请原谅我,如果已经有人问过这个问题。我有我的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]'...)";
}
答案 0 :(得分: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 */
}
我希望它有所帮助...
答案 1 :(得分:1)
我刚刚找到了解决方案。
foreach($data['cells'] as $row) {
//print_r($row);
foreach($row as $key => $value) {
echo "$key is at $value<br>";
}
}
答案 2 :(得分: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 */
}