Modify the structure of multidimensional array outputed by SQL via $wpdb
The output that I need from $wpdb is easily achievable by running multiple queries within foreach. However, I am trying to avoid the same for performance issues.
I have two custom tables:
items
- item_id
- item_name
sub_items
- sub_item_id
- item_id
- sub_item_name
The query I am running:
$items_tbl = $wpdb->prefix . 'items';
$sub_items_tbl = $wpdb->prefix . 'sub_items';
$results = $wpdb->get_results($wpdb->prepare("SELECT * from $sub_items_tbl LEFT JOIN $items_tbl ON $items_tbl.item_id = $sub_items_tbl.item_id"), ARRAY_A);
This is the resultant output of the above query:
array(
[0] => array(
['sub_item_id'] => 1
['item_id'] => 1
['sub_item_name'] => 'Lorem Ipsum'
['item_name'] => Some Item Name
)
[1] => array(
['sub_item_id'] => 2
['item_id'] => 1
['sub_item_name'] => 'Lorem Ipsum Ornare Parturient'
['item_name'] => Some Item Name
)
[2] => array(
['sub_item_id'] => 3
['item_id'] => 2
['sub_item_name'] => 'Lorem Ipsum Adipiscing Malesuada'
['item_name'] => Some Item Name
)
[3] => array(
['sub_item_id'] => 4
['item_id'] => 2
['sub_item_name'] => 'Lorem Ipsum Ligula'
['item_name'] => Some Item Name
)
[4] => array(
['sub_item_id'] => 5
['item_id'] => 2
['sub_item_name'] => 'Lorem Ipsum Sit Adipiscing'
['item_name'] => Some Item Name
)
)
And this is the output I need:
array(
[0] => array(
['item_id'] => 1
['item_name'] => Some Item Name
['sub_items'] =>[0] => array(
['sub_item_id'] => 1
['sub_item_name'] => 'Lorem Ipsum'
)
[1] => array(
['sub_item_id'] => 2
['sub_item_name'] => 'Lorem Ipsum Ornare Parturient'
)
)
[1] => array(
['item_id'] => 2
['item_name'] => Some Item Name
['sub_items'] =>[0] => array(
['sub_item_id'] => 3
['sub_item_name'] => 'Lorem Ipsum Adipiscing Malesuada'
)
[1] => array(
['sub_item_id'] => 4
['sub_item_name'] => 'Lorem Ipsum Ligula'
)
[2] => array(
['sub_item_id'] => 5
['sub_item_name'] => 'Lorem Ipsum Sit Adipiscing'
)
)
)
I'd preferably want to modify the sql to give me the resultant output. However, if that cannot be achieved then how can the output be altered in PHP?

$wpdb->prepare()behaves similar to(s)printf(). It's completely worthless if you don't use the%s/%dparts and place your vars directly in the string... – kaiser Nov 15 '12 at 14:06$wpdb->prepare()seems of no use, though I have a habit of using it every time to avoid forgetting it. – John Nov 15 '12 at 14:46$sub_items_tblare unknown to WordPress. WP can only check against default, builtin tables. Everything else has to be considered unsafe. That's why you should place%sfor every custom table name, like$sub_items_tbl. – kaiser Nov 15 '12 at 14:59