I am having some problems accessing some array data effectively and need a couple of tips.
I am doing a database call that returns data similar to this:
+------+------------+------------+-----------+
| id | key | part_num | value |
+------+------------+------------+-----------+
| 1 | application| p1 开发者_StackOverflow社区| 1|
| 2 | application| p1 | 2|
| 3 | capsule | p1 | 3|
| 3 | capsule | p1 | 4|
| 4 | instrument | p1 | 5|
| 5 | instrument | p1 | 6|
| 5 | instrument | p1 | 7|
| 1 | application| n8 | 1|
| 2 | application| n8 | 2|
| 3 | capsule | n8 | 3|
| 3 | capsule | n8 | 4|
| 4 | instrument | n8 | 5|
+------+------------+------------+-----------+
Note the part_num
I really only need the part_num and value out of this (which i am getting), but i would like to group it in PHP by the part number.
For example something even as simple as printing this:
Part: (p1)
Values: 1, 2, 3, 4, 5, 6, 7.
Part: (n)
Values: 1, 2, 3, 4, 5.
PLEASE NOTE: I can't do this with mysql as I am using this data for other things and I don't want to be doing multiple database requests.
I hope i've made this clear enough, let me know if more info is needed.
Assuming your current data is in the variable $data
you can loop through the rows and create a new array $partnums
.
$partnums = array();
foreach($data as $row) {
if (!isset($partnums[$row['part_num']]))
$partnums[$row['part_num']] = array();
$partnums[$row['part_num']][] = $row['value'];
}
Now $partnums
is an array that has the part_num's for keys... each of which references an array of values associated with that part_num.
To print out the values like you have suggested:
foreach($partnums as $partnum => $values) {
printf('Part: (%s)'.PHP_EOL, $partnum);
printf('Values: %s.'.PHP_EOL, implode(', ', $values));
}
You would use a loop go through the data. Something like this:
$results = [your query and fetch]
$array = array();
foreach ($results as $rs)
$array[$rs['part_num']][] = $rs['value'];
精彩评论