PHP - Pushing an array within another array

Asked

Viewed 347 times

3

I’m trying to make a array within another and include more data in the array from within, how do I do it ?

Follow the attempt code, it’s 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 that be:

{
    "message": "teste"
    "data": 
    {
        "login1": "login1"
        "login2": "login2"
    }
}

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 you want in json.

  • 2

    Of course... How could it not occur to me?! Better than mine

  • 1

    If you think, neither should you if a method, only has a line that we agree is simple kk +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.