Skip to content
Advertisement

PHP 7.2 – SQL Server 2017 – Create Nested Array response

I have a Stored Procedure that retrieves data from a SQL Server DB.

With query result I need to populate the parameters’ Array of a SOAPClient’s Method

At present I’m manually creating the Array, but I was wondering if it was possible (and worthy) to create the Array in the way required by the SOAP Method directly from TSQL:

Using PHP 7.2 – SQL Server 2017

Let me explain with an example: this is my Query Result:

JavaScript

While it should return something like this:

JavaScript

Is it possible and worthy?

Advertisement

Answer

You could return one row with one JSON column using FOR JSON PATH1 in SQL and in PHP json_decode($json, true)3 with $assoc param set to true to decode JSON as array.

JavaScript

The result should be JSON

JavaScript

And now You can fetch that value in PHP, decode it and supply to SOAP.

JavaScript

But in SQL You need a special syntax to format those types:

  1. date values CONVERT(varchar(10), date_col, 120)120 results in 2020-10-29 11:32:00 format, varchar(10) trim just date part, varchar(20) gets whole date+time2
  2. boolean values CAST(boolean_col as bit) (0 -> false, 1 -> true)

More info:

  1. SQL: Format query results as JSON with FOR JSON
  2. SQL: CAST and CONVERT with datetime in different formats
  3. PHP: json_decode
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement