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?

Siddharth Rathod
  • 634
  • 1
  • 7
  • 21
Peter
  • 1
  • You can push value in array like `$array['key'] = 'value'` in associative array. – Siddharth Rathod May 28 '22 at 04: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](https://www.php.net/manual/en/book.mysqli.php) or [PDO_MySQL](https://www.php.net/manual/en/book.pdo.php) extension should be used. See also the [MySQL API Overview](https://www.php.net/manual/en/mysqlinfo.api.choosing.php) for further help while choosing a MySQL API. – Dharman May 29 '22 at 16:54

1 Answers1

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);
golangphp
  • 115
  • 7