我有一个CSV数据看起来像这样:ps.csv
id|firstName|lastName|address|extId|extName
001|Kapil|Parames|address01|AA01|AA
002|David|Vuitton|address01|AA02|AA
002|David|Vuitton|address02|BB02|BB
003|Jean|Paul|address01|AA03|AA
我需要一个输出JSON,看起来像这样:
[
{
"id": "001",
"firstName": "Kapil",
"lastName": "Parames",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA01",
"extName": "AA"
}]
},
{
"id": "002",
"firstName": "David",
"lastName": "Vuitton",
"address": [{
"address": "address01"
},
{
"address": "address02"
}
],
"ext": [{
"extId": "AA02",
"extName": "AA"
},
{
"extId": "BB02",
"extName": "BB"
}
]
},
{
"id": "003",
"firstName": "Jean",
"lastName": "Paul",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA03",
"extName": "AA"
}]
}
]
我可以将其转换为JSON。但问题是我想加上"地址"。和"extName";如果该人已经存在于列表中,则将其转换为多级数组。
所以下面的PHP代码为我工作:
$csv = file('ps.csv');
$csvArray = [];
foreach ($csv as $line) {
$csvArray[] = str_getcsv($line, '|', ',');
}
$jsonArray = [];
for ($i = 1; $i < count($csvArray); $i++) {
$found = -1;
for ($j = 0; $j < count($jsonArray); $j++) {
if (in_array($csvArray[$i][0], $jsonArray[$j])) {
$found = $j;
}
}
if ($found < 0) {
$jsonArray[] = array(
'id' => $csvArray[$i][0],
'firstName' => $csvArray[$i][1],
'lastName' => $csvArray[$i][2],
'address' => array(
[
'address' => $csvArray[$i][3]
]
),
'ext' => array(
[
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
]
)
);
} else {
$addressArray = array(
'address' => $csvArray[$i][3]
);
$extArray = array(
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
);
array_push($jsonArray[$found]['address'], $addressArray);
array_push($jsonArray[$found]['ext'], $extArray);
}
}
echo '<pre>';
echo json_encode($jsonArray, JSON_PRETTY_PRINT);
echo '</pre>';
这是正确的还是有其他方法?