Skip to content
Advertisement

Issue generating proper JSON array response

Essentially I have the following PHP script that generates a response based on output of the query, I need the JSON to in a different format with each response listed sequentially:

<?php
$stmt = $pdo->prepare('

    SELECT
        `table1`.`id`, 
        `table1`.`option`
        FROM `table1`
        WHERE `table1`.`source` = 1
    ');

$stmt->execute([

]);

$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowcount = $stmt->rowCount();

if ($rowcount < 1)
{
    $response["error"] = true;
    echo json_encode($response);

}
else
{

    $response['error'] = false;
    $response['reasons'] = array_column($row, 'option', 'id');
    echo json_encode($response);

}
?>

The current response look like this:

{
  "error": false,
  "reasons": {
    "10": "Messy",
    "23": "Damaged",
    "48": "Other"
  }
}

The response I am looking for:

{
  "error": false,
  "reasons": [
    "1":{ "id": 10
          "reason": "Messy"
        }
    "2":{ "id": 23
          "reason": "Damaged"
        }
    "3":{ "id": 48
          "reason": "Other"
        }
  ]
}

How can this be achieved?’

UPDATE: Calling: $response['reasons'] = $row; Get the following result:

{
  "error": false,
  "reasons": [
    {
      "id": 10,
      "reason": "Messy"
    },
    {
      "id": 23,
      "reason": "Damaged"
    },
    {
      "id": 48,
      "reason": "Other"
    }
  ]
}

How can I get the sequential numbers to appear before the each row result?

   "1":{
      "id": 10,
      "reason": "Messy"
    },

Advertisement

Answer

If you need the indexes to start from 1 instead of 0, you need to write a loop that assigns the keys.

$reasons = [];
foreach ($row as $i => $r) {
    $reasons[$i+1] = $r;
}
$response['reasons'] = $reasons;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement