如何将简单数组转换为json格式?

时间:2014-03-21 11:36:08

标签: php arrays json

我有一个名为$ error_msg的数组,如下所示:

Array
(
    [0] =>  Please select the class 
    [1] =>  Please select the test package 
    [2] =>  Please select the section 
    [3] =>  Please select the test 
)

现在我想将其转换为json格式,如下所示:

{"error_message":"Please select the class<br>Please select the test package<br>Please select the section<br>Please select the test<br>"}

我怎样才能做到这一点?有人可以帮我这方面吗?

4 个答案:

答案 0 :(得分:6)

$string = implode("<br />", $array);
$json = json_encode( array('error_message'=>$string) );

答案 1 :(得分:3)

/*Array
(
[0] =>  Please select the class 
[1] =>  Please select the test package 
[2] =>  Please select the section 
[3] =>  Please select the test 
)*/ your array as $data
for($v=0;$v<count($data);$v++)
{
    $retrieval[$v]['id'] = $data[$v];
}
echo json_encode($retrieval);

答案 2 :(得分:0)

这应该可以解决问题

<?php

$input = array("Please select the class", "Please select the test package", "Please select the section ","Please select the test ");
$message = "";
foreach ($input as $line) {
    $message .= $line."<br/>";
}
$error = array('error_message' => $message);
echo json_encode($error, JSON_UNESCAPED_SLASHES); // Make sure slashes aren't escaped

答案 3 :(得分:0)

$error_msg  =   array
                    (' Please select the class ',
                       'Please select the test package ',
                       ' Please select the section ',
                       'Please select the test ',
                    );

echo json_encode(array('error_msg'=>join("&ltbr&gt",$error_msg)));