0

I have the following excerpt of my PHP code (web service to deliver JSON from MySql DB). I am getting a duplicate array (square brackets) in my JSON response and I'm battling with the logic of how to get rid of ONE unnecessary array. I see there's two "array_push" but I'm not sure how to manipulate it. I am weaker on constructing arrays, but learning still.

//prepare response for jsonArray type
$logdetail = array();

while ($row_result = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $row_array["timeStamp"] = $row_result["manualLog_timeStamp"];
    $row_array["type"] = $row_result["manualLog_type"];
    $row_array["value"] = $row_result["manualLog_value"];

    array_push($logdetail,$row_array);
}

// success
$response["success"] = 1;

// user device node
$response["logdetail"] = array();

array_push($response["logdetail"], $logdetail);

// echoing JSON response
echo json_encode($response);

The JSON response I get from the above is as follows (notice the unnecessary extra square/array brackets):

{"success":1,"logdetail":[[{"timeStamp":"2015-12-17 17:35:34","type":"w","value":"1000"},{"timeStamp":"2015-12-18 08:15:12","type":"w","value":"1200"},{"timeStamp":"2015-12-18 10:13:15","type":"w","value":"1300"}]]}

1 Answer 1

1

Instead of

$response["logdetail"] = array();
array_push($response["logdetail"], $logdetail);

use

$response["logdetail"] = $logdetail;

or... manipulate the response array "directly"

//prepare response for jsonArray type
$response["logdetail"] = array();
while ($row_result = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $response["logdetail"][] = array(
        "timeStamp" => $row_result["manualLog_timeStamp"],
        "type" => $row_result["manualLog_type"],
        "value" => $row_result["manualLog_value"]
    );
}
// success
$response["success"] = 1;

echo json_encode($response);
1
  • Thank you Volker! It worked. I knew it was a simple solution, just wasn't sure of it and I didn't try that. It makes complete sense to me now. Also thanks for the alternate method too. Commented Dec 19, 2015 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.