How to optimize and reduce the PHP code?

Good evening. I have the following code:
https://pastebin.com/RMKtcpH1
The first part of the code up to 47 rows to build the array $result with the SKU of the product catalog.
The second part of the code after 47 lines is iterating through the array $result and displays detailed info about each product.
Goods there are about 20,000 pieces.
Immediately there was a problem. If you try to run this code the script starts feeling and in the end gets an error 504 Gateway Timeout
The page, which gets this error - 93.90.220.244/get/treolan_productslist.php
As you can more or less optimize the code and reduce the loading time of the script?
March 20th 20 at 11:47
2 answers
March 20th 20 at 11:49
Solution
Not to make the Assembly of data on each request, to pay pre-collected data, and a demon somewhere in the background to update this information after some period of time.
March 20th 20 at 11:51
Solution
What is written in the answer above, plus

Find out if the service the ability to request multiple records.
It's possible to cache the information.

Find more questions by tags PHPArrays