在PHP中使用JSON数组时获取额外的斜杠

时间:2018-05-04 06:58:28

标签: php json

在使用PHP制作json数组时,我得到了一些额外的斜杠。我的代码如下。

<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001","subject"=>"Mathematics"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002","subject"=>"History"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001","subject"=>"Geology"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA003","subject"=>"Science"));
$result = []; // Initialize result array
foreach ($output as $key => $value) {
    $name = $value['first_name'] . ' ' . $value['last_name'];

    // check if same name already has entry, create one if not
    if (!array_key_exists($name, $result)) {
        $result[$name] = array(
            'reg_no' => $value['reg_no'],
            'name' => $name,
            'paper1' => '',
            'paper2' => '',
            'paper3' => '',
            'paper4' => ''
            );
    }

    // count array elements with value, then set paper number and value
    $paper = 'paper' . (count(array_filter($result[$name])) - 1);
    $result[$name][$paper] = $value['paper_code'].'/'.$value['subject'];
}

$result = array_values($result); // reindex result array 
echo json_encode($result);exit;
?>

这里给出了json输出。

[{"reg_no":12,"name":"robin sahoo","paper1":"BA001\/Mathematics","paper2":"BA002\/History","paper3":"BA003\/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001\/Geology","paper2":"","paper3":"","paper4":""}]

我的问题是我正在添加$value['paper_code'].'/'.$value['subject'];,而在输出中我得到了"BA001\/Mathematics"。这里添加了一个额外的斜杠(\),我需要删除它。

1 个答案:

答案 0 :(得分:2)

您可以添加JSON_UNESCAPED_SLASHES作为第二个参数。 LIke:

$result = array_values($result); // reindex result array 
echo json_encode($result,JSON_UNESCAPED_SLASHES);exit;

这将导致:

[{"reg_no":12,"name":"robin sahoo","paper1":"BA001/Mathematics","paper2":"BA002/History","paper3":"BA003/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001/Geology","paper2":"","paper3":"","paper4":""}]

Doc:json_encode()