PHP - pushing array into another array

3

I'm trying to make a array inside another and include more data in array inside, how do I do that?

Follow the code of the attempt, it is to generate a json :

$data = array(
    "login1" => "login1",
    "login2" => "login2"
);

json("teste", $data);

function json($message, $data) {

    foreach ($data as $data_chave => $data_result) {
        $json2 .= array('"'.$data_chave.'": "'.$data_result.'"');
    }

    $json = array('message' => $message, 'data' => $json2);

    echo json_encode($json);

}

The structure of json would be this:

{
    "message": "teste"
    "data": 
    {
        "login1": "login1"
        "login2": "login2"
    }
}
    
asked by anonymous 21.07.2016 / 18:24

1 answer

4
$data = array(
    "login1" => "login1",
    "login2" => "login2"
);

function json($message, $data) {
    echo json_encode(array('message' => $message, 'data' => $data));
}

json("teste", $data);

I just removed the unnecessary loop because $data is already an array and has the same structure as you want in json.

    
21.07.2016 / 18:32