Home > Blockchain >  PHP array to JSON encoded string
PHP array to JSON encoded string

Time:02-03

I want JSON in below format, from PHP array, How should I write PHP array and How should I convert it to JSON to get specific output in below format

{
  "value": [
    "01GQSE92030S8MNA78WQZ09JJQ",
    "{\n\"user_id\": \"{{current_user.id}}\",\n\"user_phone\": \"{{current_user.phone}}\",\n\"ticket_id\": \"{{ticket.id}}\",\n\"ticket_comment\": \"{{ticket.latest_comment}}\",\n\"ticket_comment_author\": \"{{ticket.latest_comment.author.name}}\",\n\"organization_id\": \"{{ticket.organization.external_id}}\",\n\"organization_name\": \"{{ticket.organization.name}}\",\n\"requester_name\": \"{{ticket.requester.name}}\",\n\"requester_phone\": \"{{ticket.requester.phone}}\"\n}"
  ]
}

I tried below PHP array with json_encode, but output is not in required format,

array(
    "value" => "01GQSE92030S8MNA78WQZ09JJQ",
    array(
        "user_id" => "{{current_user.id}}",
        "user_phone" => "{{current_user.phone}}",
        "ticket_id" => "{{ticket.id}}",
        "ticket_comment" => "{{ticket.latest_comment}}",
        "ticket_comment_author" => "{{ticket.latest_comment.author.name}}",
        "organization_id" => "{{ticket.organization.external_id}}",
        "organization_name" => "{{ticket.organization.name}}",
        "requester_name" => "{{ticket.requester.name}}",
        "requester_phone" => "{{ticket.requester.phone}}",
        "agent_external_id" => "{{current_user.external_id}}",
        "ticket_external_id" => "{{ticket.external_id}}",
        "customer_external_id" => "{{ticket.requester.external_id}}"
    )
);

CodePudding user response:

You need to encode the second entry array to JSON, also in your desired output is need to show the \n, so add second parameter JSON_PRETTY_PRINT in json_encode here is the code.

<?php

$array = [
    "value" => [
        "01GQSE92030S8MNA78WQZ09JJQ",
        json_encode([
            "user_id" => "{{current_user.id}}",
            "user_phone" => "{{current_user.phone}}",
            "ticket_id" => "{{ticket.id}}",
            "ticket_comment" => "{{ticket.latest_comment}}",
            "ticket_comment_author" => "{{ticket.latest_comment.author.name}}",
            "organization_id" => "{{ticket.organization.external_id}}",
            "organization_name" => "{{ticket.organization.name}}",
            "requester_name" => "{{ticket.requester.name}}",
            "requester_phone" => "{{ticket.requester.phone}}",
            "agent_external_id" => "{{current_user.external_id}}",
            "ticket_external_id" => "{{ticket.external_id}}",
            "customer_external_id" => "{{ticket.requester.external_id}}",
        ],JSON_PRETTY_PRINT),
    ],
];

print_r(json_encode($array,JSON_PRETTY_PRINT));

Here the live example : https://onlinephp.io/c/9efee

  • Related