Array中的字符串替换

时间:2015-01-23 04:58:04

标签: php arrays laravel replace preg-replace

以下是我对验证邮件的回复

{"success":"0","message":{"Mobile":["The mobile field is required."],"DeviceId":["The device id field is required."]}}

我的代码在哪里

$Response = array('success' => '0', 'message' => $validation->messages());
return json_encode($Response);

我想删除所有[]所以我的回复应该是

{"success":"0","message":{"Mobile":"The mobile field is required.","DeviceId":"The device id field is required."}}

我试过

$err = str_replace("[", "", $validation->messages());
$error = str_replace("]", "", $err);
$Response = array('success' => '0', 'message' => $error);
return json_encode($Response);

我正在

{"success":"0","message":"{\"Mobile\":\"The mobile field is required.\",\"DeviceId\":\"The device id field is required.\"}"}

我甚至试过

$err = str_replace("[", " ", $validation->messages());

如何执行此操作以仅删除[]以及[,以便我的输出应为

{"success":"0","message":{"Mobile":"The mobile field is required.","DeviceId":"The device id field is required."}}

3 个答案:

答案 0 :(得分:0)

你所说的你得到的是你想说的。除了“这实际上只是PHP的制作方式”之外,作为字符串的一部分。如果你回应你所得到的东西,它应该是你正在寻找的东西。

答案 1 :(得分:0)

试试这个:

$obj = json_decode($validation->messages(), true);
foreach($obj as $k=>$v) $obj[$k] = $v[0];
$validation_messages = json_encode($obj);

答案 2 :(得分:0)

$b = preg_replace('/\[|\]/', "", $validation->messages());
echo $b;