L
L
Lordao2018-07-17 21:06:53
PHP
Lordao, 2018-07-17 21:06:53

How to display data from the second table as an object?

There are two tables - product and type . The product
table has a foreign key on the typeID field of the type table . With this query, I join two tables into one result:

SELECT id, `product`.title, `product`.typeID, `type`.title FROM `product` LEFT JOIN type on `product`.typeID=`type`.typeID where `product`.typeID=1

Using a function in php json_encode()I output json. How can I display the result through php so that the typeID and title values ​​of the type table are like an object in json.
For example, here is the resulting json.
[
{
"id":"1",
"title":"Water",
"type": {
   "typeID":"3",
   "title":"liquid"
}
}
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2018-07-17
@ThunderCat

if you dream that a ready-made array will magically return from the request in this form, then nothing. Queries return one-dimensional arrays.
You can choose like this:

SELECT id, `product`.title, `product`.typeID, `type`.title, 
type`.typeID  type_typeID, type`.title  type_ttitle
FROM `product` 
LEFT JOIN `type` 
on `product`.typeID=`type`.typeID 
where `product`.typeID=1

after that, already in the code by _ split into the desired format.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question