Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

PHP script to convert Json to CSV

I've got a API JSON service and need to create a script to export data to CSV files. Does anyone have a php script to migrate JSON to CSV format?

Example Json file

  {"packWidth":200,
  "itemNo":"SEH404",
  "groupItemNo":"SEH404",
  "status":1,
  "categoryId":24356,
  "packType":"ColorBox",
  "barcode":"1234567890987",
  "modelLabel":"Color",
  "modelList":[{"key":"SEH404","value":"Black"},{"key":"SEH404W","value":"White"}],
  "packQty":20,
  "packInclude":"USB Adapter, USB Charger, Earphone, Leather Case",
  "id":3456}

An important part is the array with the tag "modelList"

The result of the array modelList, must be a column for each value

example:

packWidth, itemNo, groupItemNo, status, categoryId, packType, barcode, modelLabel, modelList1, modelList2, packQty, packInclude, id

200, SEH404, SEH404, 1, 24356, ColorBox, 1234567890987, Color, SEH404:Black, SEH404W:White, 20, USB Adapter... , 3456

Some products may also contain 5 records "modelList1-modelList2 modelList3-modelList4-modelList5. Products without modelList will record modelList empty.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please try this. Assuming $json is the raw data, so I decoded it at the beginning.

$json = json_decode($json);

// Will use $csv to build our CSV content
$csv = array();

// Need to define the special column
$modelList = 'modelList';

// Find necessary additional column number for modelList
$maxSubData = 0;
foreach ($json as $id => $data)
{
    $maxSubData = max(array(count($data->modelList), $maxSubData ));
}

// Headers for CSV file
// Headers Start
$headers = array();
foreach ($json[0] as $key => $value)
{
    if ($key == $modelList)
    {
        for ($i = 1; $i <= $maxSubData; $i++)
        {
            $headers[] = $modelList . $i;
        }
    }
    else
    {
        $headers[] = $key;
    }
}
$csv[] = '"' . implode('","', $headers) . '"';
// Headers End

// Now the rows
// Rows Start
foreach ($json as $data)
{
    $fieldValues = array();
    foreach ($data as $key => $value )
    {
        if ($key == $modelList)
        {
            $j = 0;
            foreach ($value as $subValue)
            {
                $subData = array();
                foreach ($subValue as $subCols)
                {
                    $subData[] = $subCols;
                }
                $j++;
                $fieldValues[] = htmlspecialchars(implode(':', $subData ));
            }
            for ($i = $j + 1; $i <= $maxSubData; $i++)
            {
                $fieldValues[] = '';
            }
        }
        else
        {
            $fieldValues[] = htmlspecialchars($value);
        }
    }

    $csv[] = '"' . implode('","', $fieldValues) . '"';
}
// Rows End

$finalCSV = implode("
", $csv);

print $finalCSV;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...