0

I am iterating through an array of arrays that contains sales data returning from a MySQL query:

$result = mysql_query("select salespersonId,grossProfit FROM sales");
foreach ($result as $line) {
   $salespersonId = $line['salespersonId'];
   $grossProfit = $line['grossProfit'];
}

I want to push the line into separate arrays per salespersonId (so that the 10 lines belonging to salespersonId 1 are in one array, and the 10 lines belonging to salespersonId 2 are in a different array) but I cannot seem to figure out how to do this. I've tried things like:

array_push(${'data'.$salespersonId},$line); to no avail. I feel like I might need an associative array of arrays, but you can't array_push into associative arrays. What am I missing?

2
  • You can push value in array like $array['key'] = 'value' in associative array. Commented May 28, 2022 at 4:16
  • Warning: mysql_* extension is deprecated as of PHP 5.5.0 (2013), and has been removed as of PHP 7.0.0 (2015). Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API. Commented May 29, 2022 at 16:54

1 Answer 1

0

You can do something like this

$result = mysql_query("select salespersonId,grossProfit FROM sales");
$arr = [];
foreach ($result as $line) {
   if (empty($line['salespersonId'])) {
       continue;
   }
   $arr[$line['salespersonId']][] = $line;
}
print_r($arr);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.