所以这可能是一个简单的问题,但我无法确定,我怎样才能获得数组内部的数据?我想从数组数组中的第二个元素中获取最后两个以逗号分隔的值,如果这有意义的话。
我的数组看起来像这样:
Array
(
[0] => Array
(
[0] => Print Date
[1] => Cost
[2] => Recipient
[3] => Status
[4] => Tracking #/Insurance ID
[5] => Date Delivered
[6] => Carrier
[7] => Class Service
[8] => Special Services
[9] => Insured Value
[10] => Cost Code
[11] => Weight
[12] => Mail Date
[13] => Refund Type
)
[1] => Array
(
[0] => 1/20/2016
[1] => $8.15
[2] => Justin De Los Polive, PO BOX 2353, BLANCO, TX 78606-1232
[3] => Printed
[4] => ="9405511"
[5] =>
[6] => USPS
[7] => Priority Mail (R)
[8] => USPS Tracking
[9] =>
[10] =>
[11] => 1lb 8oz
[12] => 1/20/2016
[13] => E-refund
)
[2] => Array
(
[0] => 1/20/2016
[1] => $8.15
[2] => Kist Benings, PO BOX 126, SPECULATOR, NY 12164-0026
[3] => Printed
[4] => ="9405511899563327"
[5] =>
[6] => USPS
[7] => Priority Mail (R)
[8] => USPS Tracking
[9] =>
[10] =>
[11] => 1lb 8oz
[12] => 1/20/2016
[13] => E-refund
)
[3] => Array
(
[0] => 1/20/2016
[1] => $8.92
[2] => billy flyn, PO BOX 696, P.O. BOX 696, WESTCLIFFE, CO 81252-1696
[3] => Printed
[4] => ="94063388113621"
[5] =>
[6] => USPS
[7] => Priority Mail (R)
[8] => USPS Tracking
[9] =>
[10] =>
[11] => 1lb 8oz
[12] => 1/20/2016
[13] => E-refund
)
我希望能够在第二个元素(即状态和城市)中抓取最后两个以逗号分隔的值,并将它们放入自己的元素中,这样看起来像这样:
[2] => Array
(
[0] => 1/20/2016
[1] => $8.15
[2] => Kist Benings, PO BOX 126,
[3] => SPECULATOR
[4] => NY 12164-0026
[5] => Printed
[6] => ="9405511899563327"
[8] =>
[9] => USPS
[10] => Priority Mail (R)
[11] => USPS Tracking
[12] =>
[13] =>
[14] => 1lb 8oz
[15] => 1/20/2016
[16] => E-refund
)
我的代码:
<?php
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
echo "<pre>";
print_r(csv_to_array('PrintHistory.csv'));
echo "</pre>";
die();
?>
答案 0 :(得分:0)
如果Recipient
格式相当一致:
foreach(array_column($csv, 2) as $val) {
preg_match('/(\w+), (\w{2}) [\d-]+$/', $val, $matches);
$city = isset($matches[1]) ? $matches[1] : 'none';
$state = isset($matches[2]) ? $matches[2] : 'none';
}
array_column()
从内部数组中获取所有2
索引的数组。您可能需要在循环之前执行$something = array_column()
然后unset($something[0]);
以删除标头数组。
答案 1 :(得分:0)
假设记录是一致的:
取Recipient
并将其爆炸。
输出记录是使用数组切片构建的。
守则:
// output in here
$out = array();
// lose first record...
array_shift($data);
foreach ($data as $details) {
$recipient = explode(',', $details[2]);
$outRec = array_merge(
array_slice($details, 0, 2),
array($recipient[0] .', '. $recipient[1]),
array_slice($recipient, 2, 1),
array_slice($recipient, 3, 1),
array_slice($details, 3)
);
$out[] = $outRec;
}