I have a data result being returned from my database开发者_StackOverflow社区 with multiple rows. The problem I'm having is that I only need a single row for some items and the multiple rows for others and without doing multiple database queries for every item that is needed, I thought I'd rebuild the data array.
What I am ultimately after is to use each item in the array as a string. If the last two items, product and location have multiple rows then I need them returned as strings.
What would be the best way to handle this?
Array
(
[0] => Array
(
[cid] => one line
[model] => one line
[mfgr] => one line
[color] => one line
[orderid] => one line
[product] => many lines
[location] => many lines
)
[1] => Array
(
.. repeats for as many rows as were found
)
)
Let me rephrase this question. The array that you see above is the array that is produced from my foreach. Array key [0] holds all of the data from my result. Array key[1] simply repeats the data. I need single rows for columns 1-5. Columns 6 & 7 are where I need multiple rows, hence the repeating array keys.
If I had to rebuild this array that way I need, it would look something like this:
Array
(
[single] => Array
(
[cid] => one line
[model] => one line
[mfgr] => one line
[color] => one line
[orderid] => one line
[product] => Array
(
[0] => many lines
[1] => many lines
)
[location] => Array
(
[0] => many lines
[1] => many lines
)
)
)
The kind of grouping you want to do is the kind of thing databases do best.
Lookup the MySQL documentation for GROUP_CONCAT
here.
If I understood what you need, here's how
foreach($array as $key => $value) {
if(is_array($value['product'])) {
$array[$key]['product'] = implode(', ', $value['product']);
}
if(is_array($value['location'])) {
$array[$key]['location'] = implode(', ', $value['location']);
}
}
This will turn "multiple lines" in product
and location
into a single string with commas.
精彩评论