Instead of explode
try to decode your json before to merge arrays:
json_encode(
array_merge(
json_decode($body,true),
array('MODE'=>'development')
)
)
Frage
I am trying to implement a simple middleware in Slim Framework that adds an array element in the response body. Without the middleware I am getting correct result as {"mytest":"running"}
. What I really want is to have the middle ware merge another element and make it as {"mytest":"running","MODE":"development"}
. Instead, I am getting this result {"0":"{\"mytest\"","1":"\"running\"}","MODE":"development"}
.
I am definitely missing something very simple. Please have a look below for the code I am using. I guess I am not able to convert the body to an array.
This is what I am doing:
require 'Vendor/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
//Middleware
$app->add(new \Slim\Middleware\TestMiddleware());
// Middleware Test
$app->get(
'/mid',
function () use ($app) {
$response = $app->response();
$response->body(json_encode(array(
'mytest'=>'running'
)));
}
);
namespace Slim\Middleware;
//Appends mode to the response bpoy
class TestMiddleware extends \Slim\Middleware
{
public function call()
{
$app=$this->app;
$this->next->call();
$res=$app->response;
$body=$res->getBody();
$res->setBody(
json_encode(
array_merge(
explode(":",$body),array(
'MODE'=>'development'
)))
);
}
}
Lösung
Instead of explode
try to decode your json before to merge arrays:
json_encode(
array_merge(
json_decode($body,true),
array('MODE'=>'development')
)
)