将CSV转换为JSON并使用PHP将特定键值更改为布尔值或字符串

时间:2017-01-17 05:59:28

标签: php json csv

有没有办法可以将特定的键值更改为boolean或string。转换将所有数据更改为字符串。例如,键值“Date”应该是整数而不是字符串。

<?php 

    function csvToJson($fname) {
        if (!($fp = fopen($fname, 'r') )) {
            die("Can't open file");
        }

        $key = fgetcsv($fp, "1024", ",");

        $json = array();
            while ($row = fgetcsv($fp, "1024", ",")) {
                $json[] = array_combine($key, $row);
        }

        fclose($fp);

        foreach ( $json as $k=>$v ) {


            $json[$k]['dateRequested']     = $json[$k]['DATE']; 
            $json[$k]['assignedAgent']     = $json[$k]['AGENT'];
            $json[$k]['finalCompanyName']  = $json[$k]['COMPANY NAME'];

            unset($json[$k]['DATE']);
            unset($json[$k]['AGENT']);
            unset($json[$k]['COMPANY NAME']);


        }

        return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

    }

 ?>



<?php
$json_data = csvToJson("lms.csv");
?>

2 个答案:

答案 0 :(得分:2)

试试这个:

<div class="fb-share-button" 
        data-href="<?php echo base_url()?>blog/article/<?php echo $r ->blog_id ;?>" 
        data-layout="button_count">
</div>

}

答案 1 :(得分:1)

你可以这样做:

$json[$k]['dateRequested']     = (int)($json[$k]['DATE']); 
$json[$k]['assignedAgent']     = $json[$k]['AGENT'];
$json[$k]['finalCompanyName']  = $json[$k]['COMPANY NAME'];

样本用法:

$int = (int)(123);
$bool = (bool)(1);
$string = (string)(1234);

var_dump($int);
var_dump($bool);
var_dump($string);